Trufa
Trufa

Reputation: 40717

Loop through HTML checkboxes using jQuery

I am trying to write with jQuery something that does the following.

When you click, let's say, on a paragraph, it checks to see if the checkbok is selected (checked), if it waits x amount amount of time and selects the next check box and so on.

The closest I got (not much, sorry) you can see it here.

In this example you have to click once for each check, I dont want this.

I need that when you click the <p> it:

If it is possible to loop through this, even better.

Thanks a lot in advance, I hope it is clear enough, if not, please ask!

EDIT: as @James said basically what I want is want is to

continuously loop through the checkboxes checking and unchecking them

Upvotes: 2

Views: 988

Answers (1)

James Kovacs
James Kovacs

Reputation: 11661

Do you mean something like this?

$('p').click(function() {
    $(':checkbox').each(function(i) {
        var current = $(this);
        setTimeout(function() { current.attr('checked', !current.attr('checked'))}, i*500);
    });
});

Updated jsFiddle here: http://www.jsfiddle.net/jXHTJ/2/

UPDATE: To change the order on every click (as requested in the comments) so that the checkboxes are checked/unchecked in the order {1,2,3} then {2,3,1} then {3,1,2}, you can use the following code:

(function() {
    var startWith = 0;
    $('p').click(function() {
        var checkboxes = $(':checkbox');
        var numCheckboxes = checkboxes.length;
        checkboxes.each(function(i) {
            var current = $(this);
            var delay = (i + startWith) % numCheckboxes;
            setTimeout(function() { current.attr('checked', !current.attr('checked'))}, delay*500);
        });
        startWith = ++startWith % numCheckboxes;
    });
})();

Note that I'm encapsulating the code in an anonymous function that I immediately execute so that I don't pollute the global namespace with the startWith variable. Updated jsFiddle is here: http://www.jsfiddle.net/jXHTJ/3/

Upvotes: 2

Related Questions