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: .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Category Cloud

.Net Business HTML & CSS & DOM Javascript PHP Tool

Tags

.Net ADO.NET ajax Business Javascript Oracle ADO.NET Subversion .Net Subversion SVN Source VB.Net

Recent Posts

Archives

Blogroll

Recent Comments

Asaduzzaman Arif on Encrypt/Decrypt string VB…
Pranav on Encrypt/Decrypt string VB…
ntcnet on Encrypt/Decrypt string VB…
Elena on Encrypt/Decrypt string VB…
Elena on Encrypt/Decrypt string VB…

Twitter