简体   繁体   中英

SImulate “Enter pressing” when submit button is clicked

When my submit Button in the form is clicked, I need to simulate that the "Enter button" is pressed. so: clicking on the submit form is equal to pressing Enter on the keyboard. Because I want to have the same method for both...

Here is what I have, but until now it doesnt works..

$(document).on('click', '#send', function(){
$("#chatMessageTextarea").focus();
var e = jQuery.Event("keypress");
e.which = 13;
e.keyCode = 13;

});

try something like this, not tested it, hope it helps!

function keyUpFunc(e) {
var keyCode_Enter = 13;
    if (e.keyCode === keyCode_Enter) {
        e.preventDefault();
        $('#send').trigger("click");                    
    }
}         

$(document).keyup(keyUpFunc);

$(document).on('click', '#send', function(){
    // Click Event handler for send
});

I am not sure what are you trying to achieve here. But if you want that I think this link has answer to simulate keypress via jQuery.

Definitive way to trigger keypress events with jQuery

Copied code from link:

var e = jQuery.Event("keydown");
e.which = 13; // # Some key code value
$("input").trigger(e);

Try this:

$(document).on('click', '#send', function(){
   $("#chatMessageTextarea").trigger({
        type: "keypress", 
        which: 13, 
        keyCode: 13});
});

hope it helps!

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