Benno
Benno

Reputation: 149

How to make a JQuery Script Only Fire Once

I have a JQuery script that selects the right radio button on a wordpress-plugin form and then hits the update button. The problem is that the update button reloads the script causing an infinite loop.

How can I make sure the script only does its job once?? This is the code I'm using:

$(document).ready(
    function()
    {
       $('input[value="Yes"]').attr('checked', 'checked');
       $(".update-button").trigger('click');
    }
 );

Upvotes: 3

Views: 1241

Answers (1)

Elliot Bonneville
Elliot Bonneville

Reputation: 53331

One option is to store a value when you click update in an area that won't be lost when the page is refreshed. When the page is refreshed, then check to see if that value is still there. If it is, don't re-execute the script. I chose to use localStorage for my example, but cookies work just as well:

$(document).ready(function(){
    if(!localStorage.updated) {
        $('input[value="Yes"]').attr('checked', 'checked');

        $(".update-button").trigger('click');
        localStorage.updated = "true";
    }
});

Upvotes: 2

Related Questions