How to use simulate the action of clicking button with jQuery or JavaScript?

JavascriptJquery

Javascript Problem Overview


I need to use JavaScript to simulate the action of clicking buttons. How do I achieve it? Can I achieve it with jQuery?

Javascript Solutions


Solution 1 - Javascript

Yes, you can do it with jquery. Use trigger function. Here documentation. Here is sample:

$('#foo').trigger('click');

Solution 2 - Javascript

You can execute the click event handler assigned to a button control:

$("#mybutton").click();

Solution 3 - Javascript

Simply .click():

$("#theButton").click();

Solution 4 - Javascript

Please try following code e.g.:

setTimeout(function() {
    $(".class_name").trigger('click');	
}, 2000);

Solution 5 - Javascript

Following code will print clicked two times one from $('.submitBtn').click(); and other $('.submitBtn').trigger('click')

$(document).ready(function() {

  $('.submitBtn').on('click', function() {

   console.log("Clicked!");

  })

$('.submitBtn').click();
$('.submitBtn').trigger('click')



});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button menu="submitBtn" class="submitBtn len4 btn" title="submit" data-code-m="sbm.submit"> Click me
        </button>

Solution 6 - Javascript

Wrapping it in this 'anonymous document ready function' will make sure the button is there before you click it. Just in case it tries to click before the element you want to click is loaded. This would fix that issue.

Also, remember that an ID uses a hash (i.e. #close-button) but if you want to click an element that has a CLASS then swap the hash for a single dot (i.e. .close-button).

jQuery(document).ready(function() {
		$("#close-button").trigger('click');	
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRickyView Question on Stackoverflow
Solution 1 - JavascriptgorView Answer on Stackoverflow
Solution 2 - JavascriptjevakallioView Answer on Stackoverflow
Solution 3 - JavascriptPeter ÖrneholmView Answer on Stackoverflow
Solution 4 - JavascriptApurv ChaudharyView Answer on Stackoverflow
Solution 5 - JavascriptNisal EduView Answer on Stackoverflow
Solution 6 - JavascriptGary Carlyle CookView Answer on Stackoverflow