简体   繁体   中英

How do I simulate events (other than focus and blur) on an html form input element?

Html has many event types. I'm trying to simulate login with javascript code in a .hta . I try the following on a text input element:

user.focus();
user.value = 'JohnDoe';
user.blur();
button.click();

Yet the page responds as if I had clicked the button without entering a user name. I suspect that an event handler is registered on the element which isn't fired when I do this with a script. What van I do to establish the cause of the failure and amend it? How do I simulate the other event types on the element?

I found the answer here: How to trigger event in JavaScript?

Here's the recipe:

function fireevent(type, ele)
{
    var event = win.document.createEvent("HTMLEvents");
    event.initEvent(type, true, true);
    ele.dispatchEvent(event);
}

Where win is the window in question. fireevent('change', user) fires a change event on the text input element user, and that was what I needed to do. Now it works :)

Beware though that createEvent is now deprecated. On IE10, which is the one I use with .hta, it works just fine.

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