Trigger a button click with JavaScript on the Enter key in a text box

后端 未结 30 1997
难免孤独
难免孤独 2020-11-21 23:53

I have one text input and one button (see below). How can I use JavaScript to trigger the button\'s click event when the Enter key is pressed ins

30条回答
  •  走了就别回头了
    2020-11-22 00:48

    In jQuery, you can use event.which==13. If you have a form, you could use $('#formid').submit() (with the correct event listeners added to the submission of said form).

    $('#textfield').keyup(function(event){
       if(event.which==13){
           $('#submit').click();
       }
    });
    $('#submit').click(function(e){
       if($('#textfield').val().trim().length){
          alert("Submitted!");
       } else {
        alert("Field can not be empty!");
       }
    });
    
    
    
    

提交回复
热议问题