Detect the Enter key in a text input field

后端 未结 10 709
粉色の甜心
粉色の甜心 2020-11-29 16:20

I\'m trying to do a function if enter is pressed while on specific input.

What I\'m I doing wrong?

$(document).keyup(function (e) {
    if ($(\".inpu         


        
相关标签:
10条回答
  • 2020-11-29 16:48

    The solution that work for me is the following

    $("#element").addEventListener("keyup", function(event) {
        if (event.key === "Enter") {
            // do something
        }
    });
    
    0 讨论(0)
  • 2020-11-29 16:50

    Try this to detect the Enter key pressed in a textbox.

    $(function(){
    
    $(".input1").keyup(function (e) {
        if (e.which == 13) {
            // Enter key pressed
        }
     });
    
    });
    
    0 讨论(0)
  • 2020-11-29 16:53
    $(document).keyup(function (e) {
        if ($(".input1:focus") && (e.keyCode === 13)) {
           alert('ya!')
        }
     });
    

    Or just bind to the input itself

    $('.input1').keyup(function (e) {
        if (e.keyCode === 13) {
           alert('ya!')
        }
      });
    

    To figure out which keyCode you need, use the website http://keycode.info

    0 讨论(0)
  • 2020-11-29 16:55
    $(".input1").on('keyup', function (e) {
        if (e.key === 'Enter' || e.keyCode === 13) {
            // Do something
        }
    });
    
    // e.key is the modern way of detecting keys
    // e.keyCode is deprecated (left here for for legacy browsers support)
    // keyup is not compatible with Jquery select(), Keydown is.
    
    0 讨论(0)
  • 2020-11-29 16:56

    The best way I found is using keydown ( the keyup doesn't work well for me).

    Note: I also disabled the form submit because usually when you like to do some actions when pressing Enter Key the only think you do not like is to submit the form :)

    $('input').keydown( function( event ) {
        if ( event.which === 13 ) {
            // Do something
            // Disable sending the related form
            event.preventDefault();
            return false;
        }
    });
    
    0 讨论(0)
  • 2020-11-29 16:57

    This code handled every input for me in the whole site. It checks for the ENTER KEY inside an INPUT field and doesn't stop on TEXTAREA or other places.

    $(document).on("keydown", "input", function(e){
     if(e.which == 13){
      event.preventDefault();
      return false;
     }
    });
    
    0 讨论(0)
提交回复
热议问题