Posted by: Matthew | February 14, 2008

Clicking a button in Javascript doesn’t always work 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();
}

Advertisement

Responses

  1. I have created an input type =file which is hidden and try to trigger using a button which means when I click the button, it should trigger the input file using its click()…I tried using ur method but it still doesnt work in firefox…works fine in IE….any ideas?

  2. PERFECT – You saved me some time on this one… thanks a ton. Glad I stumbled upon this blog.

    Appreciate you writing this up! Thanks a million.


Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.