2013-05-07 77 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/