2013-05-07 74 views
1

点击“select all”复选框后,我想选中所有复选框。 Here`s是代码使用jquery选择div内的所有复选框

<div class="fp"> 
    <div class="fpanel"> 
    <div class="fpblockscontainer"> 
     <span class="fpblockslabel">Merchants</span>  
     <div class="fpblocks"> 
     <label class="checkbox"> 
      <input class=".select-all2" type="checkbox">Select All</label> 
     <label class="checkbox"> 
      <input type="checkbox">Apple</label> 
     <label class="checkbox"> 
      <input type="checkbox">orange</label> 
     <label class="checkbox"> 
      <input type="checkbox">potato</label> 
     <label class="checkbox"> 
      <input type="checkbox">Williams-Sonoma</label> 

     </div> 
    </div> 

在这里,我需要一旦选择了“select.all2”复选框以选择所有的复选框。下面的jQuery代码不起作用。我错在哪里?

$(".select-all2").on("click", function() { 
    if ($(this).is(':checked')) { 
    $(this).closest("div.fp").find(':checkbox').each(function() { 
     $(this).attr('checked', 'checked'); 
    }); 
    } else { 
    $(this).closest("div.fp").find(':checkbox').each(function() { 
     $(this).removeAttr('checked'); 
    }); 
    } 
}); 

回答

5

只是从你的输入中删除点,和它应该工作正常

<input class=".select-all2" type="checkbox" > 

<input class="select-all2" type="checkbox" > 

在这里看到:jsFiddle Demo

4

从类中删除.

<input class="select-all2" type="checkbox" > 
     //------^----here 

使用道具()而不是ATTR()

$(this).prop('checked', true); //to check the checkbox 

$(this).prop('checked', false); //to uncheck the checkbox 

,你不需要每次()循环

试试这个

$(".select-all2").on("click", function() { 
    if ($(this).is(':checked')) { 
     $(this).closest("div.fpblocks").find(":checkbox").prop('checked',true); 

    } else { 
     $(this).closest("div.fpblocks").find(":checkbox").prop('checked',false); 
    } 
}); 

fiddle here

0

请尝试此选择/取消选择。当个别复选框也被选中/取消选中时,这将改变select-all2的状态。

var $ch = $(".select-all2").change(function() { 
    $all.prop('checked', $ch.filter(':checked').length == $ch.length); 
}), 
$all = $('.checkbox input[type=checkbox]').click(function() { 
    $ch.prop('checked', this.checked); 
}); 

demo

3

的点击也不会解雇了,因为标记包括类名的.

<input class=".select-all2" type="checkbox" > 

应该是:

<input class="select-all2" type="checkbox" > 

脚本还可以更加简洁:

$(".select-all2").click(function(){ 
    $("input[type='checkbox']").prop("checked", $(this).is(":checked")); 
}); 

工作实例http://jsfiddle.net/uY8yu/