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

前端 未结 4 1651
忘掉有多难
忘掉有多难 2020-12-29 02:02

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

相关标签:
4条回答
  • 2020-12-29 02:15
    $(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!');
        });
    
    });
    
    0 讨论(0)
  • 2020-12-29 02:17

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

    $('#myText').keydown(function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
        }
        alert(e.keyCode);
    });
    
    0 讨论(0)
  • 2020-12-29 02:22

    Try this:

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

    Demo

    0 讨论(0)
  • 2020-12-29 02:32

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

    $(document).on("keypress", ".myText", function(e) {
         if (e.which == 13) {
             //do some stuff
         }
    });
    
    0 讨论(0)
提交回复
热议问题