How to use simulate the action of clicking button with jQuery or JavaScript?
JavascriptJqueryJavascript 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');
});