Simulate a button click via JavaScript

There is a rare need for this type of functionality but I have found myself in a couple of situations where I needed it. Here is a quick demo of a button click that is simulated from another event handler. In this case, the button click is invoked by checking a checkbox.

Demo

Check the box to simulate a button click



Here is the HTML code including the JavaScript:

1
2
3
<input type="checkbox" onClick="document.getElementById('theSubmitButton').click();">Check the box to simulate a button click
<br>
<input type="button" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">

If the button is clicked directly, a JavaScript alert will pop up with the following message:

The button was clicked.

The onClick event handler for the checkbox will access the HTML DOM button object and invoke the click() method. This simulates the button click and invokes the alert.

If you found that my code was helpful in any way, shape, or form and would like to buy me a beer, please use the Donate button below =) Cheers!