views:

354

answers:

3

I have the following javascript code:

function ClickButtons() {
   document.getElementById('Button1').click();
   document.getElementById('Button2').click();
}

only Button2 seems to be clicked. If I reverse the order of the statements then only Button1 (which would be called 2nd then) seems to work.

FYI (don't think this is impacting this issue, here for futher information): The button clicks are doing ajax/partial page updates (they call data services and populate data on the page)

EDIT: The solution setTimeout works, but puts an lower bound on performance. I've done a bit more looking and the two buttons are asp.net buttons and are inside update panels. If I click them sequentially they work fine, but if i click one and then quickly click a second one (before the first has completed) then the second one will work and the first will fail. This appears to be an issue with update panels and asp.net? Is there anything I can do on that front to enable the above javascript and avoid the setTimeout option?

A: 

They should both fire a click event. What happens if you remove your ajax requests and other heavy lifting and just put an alert or console.log in each event listener. Oh, and how are you listening to events?

apphacker
+1  A: 

It should work. Try putting a setTimeout call for the second button after the first button is clicked. It's ugly but maybe it will work.

function clickButton() {
 document.getElementById('#button1').click();
 setTimeout(button2, 300);
}

function button2() {
 document.getElementById('#button2').click();
}
rymn
how about clearing the timeout?
Greco
fantastic this fixed my immediate problem, thanks again
ChrisHDog
Welcome. Forgot to mention that you need to clear the timeout.
rymn
+1  A: 

How about using IE's fireEvent() function?

function ClickButtons() {
  document.getElementById("Button1").fireEvent("onclick");
  document.getElementById("Button2").fireEvent("onclick");
}

Working example (tested in IE6):

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Click Test</title>
  </head>

  <body>
    <button id="Button1" onclick="alert('Button1 Clicked');">Click 1</button>
    <button id="Button2" onclick="alert('Button2 Clicked');">Click 2/button>
    <script type="text/javascript">
      document.getElementById("Button1").fireEvent("onclick");
      document.getElementById("Button2").fireEvent("onclick");
    </script>
  </body>
</html>

Since your use of click() is to my knowledge IE-specific, so is this answer. Events are fired differently in different browsers, but it shouldn't be too tough to make wrappers and hide the difference.

Zack Mulgrew
+1 this has the same issue as the other one, it appears to be "updatepanel" related ... thanks for the information though
ChrisHDog