user2945911
user2945911

Reputation: 3

jquery checkbox select all

I've got jquery all set up to find my select All check box, but for some reason it only selects all on the second click.

Any ideas would be greatly appreciated.

    $("h2 #selectAllState").click(function () {

  var here = $(this).closest("div").attr('id');
  var stateDiv = "#"+here;
  var cityList = "#state"+here;


$(stateDiv+" h2 input:checkbox").change(function () {
        $(cityList).find(':checkbox').prop("checked", this.checked);
    });

});

Or is a jfiddle

Upvotes: 0

Views: 151

Answers (1)

Jason P
Jason P

Reputation: 27022

Your original issue was that you weren't binding the change handler until the first click happened. I've fixed that and managed to simplify your code using traversal functions.

http://jsfiddle.net/w8ZLV/

$("#selectAllState").click(function () {    
    $(this).closest('div').find('.cityPick :checkbox').prop("checked", this.checked);
});

Additionally, it looks like you might be repeating this block for other states, in which case you could have more than one element with the id #selectAllState, which isn't allowed. If my assumption is correct, that should be changed to a class instead of an id.

Upvotes: 6

Related Questions