简体   繁体   中英

Simulate Pressing Enter Key to Submit (NO jquery)

I'm trying to figure out a way to submit what's in the textbox automatically by simulating hitting Enter Key.
We want to avoid using submit() so I'm trying to find a way to submit by simulating enter key.

I want to use strict Javascript without jquery.

Would you be able to review the code below and how I can simulate hitting Enter Key after populating the value in the text box?

I'm new to Javascript so please be patient with me. Let me know if you need anything.

This is my current script:

//Find reason then populate text box
function FillText() {
    var TextField = document.getElementsByName("reason");
    TextField[0].value = "TEST";
}

var delayInMilliseconds = 6000; //6 second
setTimeout(function() {
    FillText();
}, delayInMilliseconds);

How should I modify FillText function so it would work? (Compared to my original script?)

//Find reason then populate text box
function FillText() {
    var TextField = document.getElementsByName("reason");
    TextField[0].value = "TEST";

    var evt = new KeyboardEvent("keydown", {
    bubbles: true, cancelable: true, keyCode: 13
    });
    TextField[0].dispatchEvent(evt);
}

Edit / Note: Most of the previous posts refer to initKeyboardEvent which applies to Firefox. I'm looking for one that will work with Chrome and with other browsers using strictly Javascript.

Try this:

var evt = new KeyboardEvent("keydown", {
    bubbles: true, cancelable: true, keyCode: 13
});
element.dispatchEvent(evt);

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