0

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

4

1 回答 1

6

change您最初的问题是在第一次单击发生之前您没有绑定处理程序。我已经解决了这个问题,并设法使用遍历函数简化了您的代码。

http://jsfiddle.net/w8ZLV/

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

此外,看起来您可能会为其他状态重复此块,在这种情况下,您可能有多个具有 id 的元素#selectAllState,这是不允许的。如果我的假设是正确的,那应该改为类而不是 id。

于 2013-11-01T18:02:42.420 回答