jquery .click() does not work

87 views Asked by At

on my php page I want to click a button on page load. I have tested it with jQuery and JS. While jQuery does not work, the JS works fine.

Any idea why this is the case?

jQuery:

<script>
$(document).ready(function() {
    $('#button_id').click();
    $('#button_id').trigger('click');
});
</script>

JS:

<script>
    window.onload = function() {
        document.getElementById('button_id').click();
    };
</script>

The button I want to click has a data-filter inside. Might this be the problem?

<button id="button_id" data-filter=".parkett" class="sub">Button</button>

EDIT:

No errors in the console, libary is added at the top.

This is my console output if I log both buttons:

Screenshot of console

3

There are 3 answers

0
mayur kasar On BEST ANSWER
$("document").ready(function() {
setTimeout(function() {
    $("#button_id").trigger('click');
},10);
});
2
Seann On

Sounds like you haven't included the jquery script in your head

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

$('#button_id').click();

You have defined no click handler - so nothing going to happen. You need to drop a function in there to use as the callback. Like this:

 $( "#button_id" ).click(function() {
    $(this).trigger('click');
 });