I need to use JavaScript to simulate the action of clicking buttons. How do I achieve it? Can I achieve it with jQuery?
6 Answers
Yes, you can do it with jquery. Use trigger function. Here documentation. Here is sample:
$('#foo').trigger('click');
3 Comments
.click() method? Is there perhaps some runtime cost difference between the two?$(this).trigger('click');event.preventDefault();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>
Comments
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');
});