2011-05-26 117 views
16

檢查我將如何實現這一目標:檢查,如果輸入的使用jQuery

if($(this).parent().find('input:checked') == true) 

{$(this).find('.switch').attr('state','on');} 
else{$(this).find('.switch').attr('state','off');} 

我知道這是錯誤的,但你的想法,我認爲:)。如果有一個被檢查的輸入,則添加狀態,如果沒有關閉狀態。

+0

你能顯示您的標記,此代碼一些更多的背景?很難知道所提供的解決方案是否從這一部分準確無誤。 – mVChr 2011-05-26 20:27:32

回答

34

嘗試用

if($(this).parent().find('input').is(':checked')) { 
    something(); 
} 

這個作品,如果只有一個複選框。

1

嘗試這樣做:

if ($(this).parent().find('input:checked').length > 0) {  
    $(this).find('.switch').attr('state','on'); 
} else { 
    $(this).find('.switch').attr('state','off'); 
} 

這裏假設你有$(this).parent()

6

範圍內只有1個輸入它不一定是錯的,但選擇返回適用於該條件的所有元素。因此,你必須檢查,如果長度不爲0:

if($(this).parent().find('input:checked').length) 
3

這也適用,如果你知道輸入HTML元素的ID:

if($('input#element_id_name:checked').length>0) { 
    //your code here. 
} 
3

Supposign input[type=checkbox] = this,您可以檢查元素本身。

來源:jQuery docs

$("input[type=checkbox]").change(function(){ 
    if (this.checked){} 
    //or 
    if ($(this).prop("checked")){} 
    //or 
    if ($(this).is(":checked")){} 
}); 
0

如果你知道ID,只需使用:

if ($("#myCheckBox").is(":checked")) { 

}