简体   繁体   中英

Trigger click after load page

I'm working with a wordpress theme and I need to activate a button when the page loads, but none of the following has worked for me (my button has the ID "reset"):

$(document).ready(function() {
   $("#reset")[0].click();
}); 

--

$(document).ready(function(){
   $("#reset").click();
})

--

$(window).load(function(){
      $('#reset').click();
});

I put the code in the header or in the page where i need to activate the button, but does not work.

Thanks!

JavaScript does not allow seamless programmatic triggering of an actual click event.

What you could do is

  1. declare the click callback as a separate, named function

eg

function myClickCallback(e) {
  // Do stuff here
}
  1. Set this as the click callback of your button (eg $('#reset').on('click', myClickCallback) ).

  2. Invoke the callback when the page loads (eg $(document).ready(myClickCallback); )

I am not sure why you 'd want this functionality, since it sounds weird. From reading your description, by "activating", you could also mean enabling the button. To do that you should do something like the following

$(document).on('ready', function (e){
    $('#reset').removeAttr('disabled');
});

You may need to refer to it using jQuery instead of $ :

The jQuery library included with WordPress is set to the noConflict() mode...

https://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers

$(document).ready(function(){
 $("#reset").trigger('click');
});

I give you example here

$(document).ready(function(){
   $("#reset").click();
})

the code above should work.

Use the function Trigger with the event click

$(document).ready(function(){
 $("#reset").trigger('click');
});

This what works for me:

$(function () {
        $('#btnUpdatePosition').click();  
});

On the button event, the JQuery binding event doesn't work:

$('#btnUpdatePosition').click(function () {
            alert('test again');
        });

But it works when I added the event on attribute declaration:

<input type="button" value="Update" id="btnUpdatePosition" onclick="alert('Click has been called')" />

You can also call if you have a function on element:

<input type="button" value="Update" id="btnUpdatePosition" onclick="fncShow();" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM