How to get the Enter key within a textbox to trigger a function and not the first/default button

蹲街弑〆低调 提交于 2019-11-30 06:04:20
sachleen

Try this:

$('#myText').on("keypress", function(e) {
        if (e.keyCode == 13) {
            alert("Enter pressed");
            return false; // prevent the button click from happening
        }
});

Demo

Arvind Bhardwaj

Use .on() as .live() has been deprecated.

$(document).on("keypress", ".myText", function(e) {
     if (e.which == 13) {
         //do some stuff
     }
});
Suraj Chandran

Do e.preventDefault() in keyDown to avoid default action of button:

$('#myText').keydown(function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
    }
    alert(e.keyCode);
});
$(document).ready(function() {

    $('#myText').keypress(function(e) {
        if ( e.keyCode == 13 ) {  // detect the enter key
            $('#myButton').click(); // fire a sample click,  you can do anything
        }
    });

    $('#myButton').click(function(e) {
        alert('Button click activated!');
    });

});

DEMO

For live elements use .on() like below:

$(document).ready(function() {

    $(document).on('keypress', '#myText', function(e) {

        if ( e.keyCode == 13 ) {  // detect the enter key
            $('#myButton').click(); // fire a sample click,  you can do anything
        }
    });

    $(document).on('click', '#myButton', function(e) {
        alert('Button click activated!');
    });

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!