How to trigger HTML button when you press Enter in textbox?

后端 未结 12 1250
悲哀的现实
悲哀的现实 2020-12-04 08:13

So the code that I have so far is:

&
相关标签:
12条回答
  • 2020-12-04 09:02

    First of all add jquery library file jquery and call it in your html head.

    and then Use jquery based code...

    $("#id_of_textbox").keyup(function(event){
        if(event.keyCode == 13){
            $("#id_of_button").click();
        }
    });
    
    0 讨论(0)
  • 2020-12-04 09:03

    You could add an event handler to your input like so:

    document.getElementById('addLinks').onkeypress=function(e){
        if(e.keyCode==13){
            document.getElementById('linkadd').click();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 09:06
    $(document).ready(function(){
        $('#TextBoxId').keypress(function(e){
          if(e.keyCode==13)
          $('#linkadd').click();
        });
    });
    
    0 讨论(0)
  • 2020-12-04 09:09

    This should do it, I am using jQuery you can write plain javascript.
    Replace sendMessage() with your functionality.

    $('#addLinks').keypress(function(e) {
        if (e.which == 13) {
            sendMessage();
            e.preventDefault();
        }
    });
    
    0 讨论(0)
  • 2020-12-04 09:11

    It works when input type="button" is replaced with input type="submit" for the default button which needs to be triggered.

    0 讨论(0)
  • 2020-12-04 09:12
    1. Replace the button with a submit
    2. Be progressive, make sure you have a server side version
    3. Bind your JavaScript to the submit handler of the form, not the click handler of the button

    Pressing enter in the field will trigger form submission, and the submit handler will fire.

    0 讨论(0)
提交回复
热议问题