Dynamically Click on a Button with JavaScript

Today I ran into a case where I needed to emulate a button click. How did I imitate a button click? Here is how I did it with a little JavaScript and the click function.

Emulate Button Click with JavaScript

Imagine you have a button with the id of mybutton:

document.getElementById(‘mybutton’).click();

The above JavaScript line will click on that button. What I needed to do is to have a button clicked when someone clicks on a div. Note that it could be any element that is clicked on such as another button or even an image. I did this:

<div style=”width:400px;height:225px;border:1px solid red;” onclick=”document.getElementById(‘buttonb’).click();” />Click on this div to click the submit button…</div>

<input type=”submit” id=”buttonb” name=”buttonb” value=”” />

In the above example, when the user clicks on the div that says “Click on this div to click the submit button…”, the submit button is clicked and whatever form it goes to is submitted. There are various reasons why you might need to use this trick and it is a good one to have in your bag. Notice I added styles to the div to make it visible.

Leave a Reply

Your email address will not be published. Required fields are marked *