简体   繁体   中英

How do I enter jquery with the “Enter” key or Button?

I have a javascript function that works fine if the user clicks the button assigned. If the user hits the enter key I get an error. Is there a way to trigger jquery code with either?

$(document).ready(function() {
    $("#btnAdd").click(function() {
        //execute from click or enter key
    });
});

You could do something like the following assuming you're entering data in a textbox and trying to capture the enter key:

$(document).ready(function() {
  $("#textBox").live("click", function() {
        //if enter key is pressed
        if(e.keyCode == 13) {
                //click the button and go to next page
                $("#btnAdd").click();
        }               
  });   
});
$('body').keyup(function(e) {
    if(e.keyCode == 13) {
        //Enter button pressed
        runCode();
    }
});

$("#btnAdd").click(function() {
    runCode();
});

Hopefully this is usefull!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM