2012-12-07 106 views
2

我有這樣的:jQuery的複選框選中

<div id="container1"> 
    <div class="block1"> 
     <input class="pos2" type="checkbox" /><label>Category1</label><br> 
     <input class="pos3" type="checkbox" /><label>Subcategory1</label><br> 
     <input class="pos3" type="checkbox" /><label>Subcategory1</label> 
    </div> 

    <div class="block1"> 
     <input class="pos2" type="checkbox" /><label>Category2</label><br> 
     <input class="pos3" type="checkbox" /><label>Subcategory2</label> 
     <input class="pos3" type="checkbox" /><label>Subcategory2</label> 
    </div> 
</container> 

我試圖使用jQuery自動檢查複選框。例如:如果我檢查'pos2',它會自動檢查pos3。

我用這個:

$("#container1 .block1 .pos2").click(function(){ 
    $(".block1").children(".pos3").attr('checked', 'checked'); 
}); 

但我需要它只是從我點擊了DIV檢查「POS3」。

注意:複選框由來自entrys的PHP在數據庫中生成。他們的數字可能會有所不同,因此我不能在元素上使用ID。

任何人都可以幫助我嗎?

在此先感謝!在處理函數

$("#container1 .block1 .pos2").click(function(){ 
    $(this).parent().find('.pos3').attr('checked', 'checked'); 
}); 

this點,點擊的對象:

回答

1

試試這個:

$(".pos2").click(function(){ 
    $(this).siblings(".pos3").attr('checked', 'checked'); 
}); 
0

此代碼應工作。 .parent會得到複選框的父母發現將爲.pos3僅搜索父DIV中(如$(".block1 .pos3")

+0

非常感謝您!你救了我! :) – user1885099

+0

@ user1885099而不是「謝謝」評論,JFYI:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work。另外,BuddhiP用'.siblings'的答案更好 - 它更短,並且做同樣的事情。另外它應該更快。 –

0

嘗試以下

$("#container1 .block1 .pos2").click(function(){ 
    $(this).parents("div.block1:first") 
    .children(".pos3").attr('checked', 'checked'); 
}); 
0
$("#container1 .block1 .pos2").click(function(){ 
$(this).siblings(".pos3").attr('checked', 'checked'); 
}); 
1
$("#container1 .block1 .pos2").on('change', function(){ 
    $(this).siblings('.pos3').prop('checked', this.checked); 
});