How to get the Enter key within a textbox to trigg

2019-02-03 23:54发布

I am trying to get the Enter key to trigger a function when it is pressed when inside a certain textbox, and not trigger the first or default button.

You can see an example of what is happening here: http://jsfiddle.net/cutsomeat/WZ6TM/1/

If you press other keys you will get an alert box with the keycode, yet if you press the Enter key you will not get the alert box with the keycode, but rather the alert box within the button click event.

Obviously the Enter key is trigger the button. Is there a way to avoid this and instead, capture the Enter key in the keyup event, then trigger another function?

4条回答
该账号已被封号
2楼-- · 2019-02-04 00:10

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

$('#myText').keydown(function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
    }
    alert(e.keyCode);
});
查看更多
Summer. ? 凉城
3楼-- · 2019-02-04 00:14
$(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!');
    });

});
查看更多
成全新的幸福
4楼-- · 2019-02-04 00:21

Try this:

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

Demo

查看更多
甜甜的少女心
5楼-- · 2019-02-04 00:23

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

$(document).on("keypress", ".myText", function(e) {
     if (e.which == 13) {
         //do some stuff
     }
});
查看更多
登录 后发表回答