2011-12-05 22 views
3

我有幾個checkbox元素,我想禁用下一個(或前一個)。jQuery:搜索下一個複選框並禁用它

我的代碼如下所示:

<td> 
    <input type="checkbox" class="chkOk" /> 
</td> 

<td> 
    <input type="checkbox" class="chkNotOk" /> 
</td> 

<!-- Futher checkboxes --> 

我想:

$(function() { 
    $('input[type=checkbox]').bind("click", function() { 
     $(this).next('input[type=checkbox]').attr("disabled"); 
    }); 
}); 

而且也:

$(this).siblings('input[type=checkbox]').attr("disabled"); 

但它不工作。請幫忙。

+2

你使用'attr'的方式有* getter *而不是* setter *;你有沒有嘗試過使用'.attr(「disabled」,true);'? – jabclab

回答

13

你必須去到父td,發現從那裏下一個複選框:

var n = $(this).parent().nextAll().has(":checkbox").first().find(":checkbox"); 

這得到使用parenttd,然後獲取td以下所有的兄弟姐妹(nextAll)將匹配集減少爲僅包含複選框(has)的那些td元素,然後獲取其餘集中的第一個(first)。

注意disabled是一個屬性,你應該用prop來設置它,而不是attr

n.prop("disabled", true); 

您遇到的問題,是因爲你正在尋找的點擊複選框的兄弟姐妹,並在你的示例HTML他們沒有任何兄弟姐妹。

+0

非常感謝 –