Clicking a button in Javascript doesn’t always work in Firefox
July 23, 2008
Clicking a button in Javascript always work in IE but not in Firefox.
I’ve run into a javascript problem a few times which -for a refreshing change – shows itself as Firefox not behaving as you might expect (… well Firefox together with ASP.NET at any rate).
The issue surfaces when you try and invoke a button click on an input element of type “submit” through javascript. Simply use myButton.click() you say? Well, unfortunately no. It can be the case that the click appears to work in terms of invoking any other javascript that might be attached to that event, but it actually does not invoke the postback to the server. The button works perfectly when use the mouse, but just doesn’t work with the click() method.
So the solution is to fake the button being clicked with the mouse when in firefox, and otherwise to just use what you’d expect:
if (button.dispatchEvent)
{
var e = document.createEvent(“MouseEvents”);
e.initEvent(“click”, true, true);
button.dispatchEvent(e);
}
else
{
button.click();
}
Entry Filed under: Javascript. Tags: Javascript.
Trackback this post | Subscribe to the comments via RSS Feed