Javascript submit textbox on ENTER [duplicate]

2019-01-24 04:58发布

问题:

Possible Duplicate:
Bind textbox to 'enter' key

I've made ajax / jquery chat and there is no form in textbox for message , so i can't submit that message with ENTER on keyboard.Is there any way to submit that value from textbox with javascript ?

Thanks.

回答1:

document.getElementById("id_of_your_textbox").addEventListener("keydown", function(e) {
    if (!e) { var e = window.event; }
    e.preventDefault(); // sometimes useful

    // Enter is pressed
    if (e.keyCode == 13) { submitFunction(); }
}, false);


回答2:

$('#textboxId').keydown(function (event) {
    var keypressed = event.keyCode || event.which;
    if (keypressed == 13) {
        $(this).closest('form').submit();
    }
});

If you don't have form, then replace $(this).closest('form').submit(); with whatever AJAX/submit logic you have.



回答3:

You will need to listen for the ENTER key press event. Take a look at Enter key press event in JavaScript for some examples on how it is done.