2011-10-19 71 views
2

如果複選框被選中,如何禁用文本框。 我有幾個文本框和複選框彼此相鄰。如果複選框被選中,jquery禁用下一個元素

HTML:

$("input[name=deposit_checked]").change(function(){ 

if($("input[name=deposit_checked]").is(":checked")) { 
    $("input[name=deposit_value]").attr("disabled", false); 
} else { 
    $("input[name=deposit_value]").attr("disabled", true); 
} 

}) 

爲了節省時間,我嘗試使用。每()和的.next()函數,但沒有運氣:

<form id="form"> 
<input type="checkbox" name="deposit_checked"> <input type="text" name="deposit_value"> 
<input type="checkbox" name="booking_checked"> <input type="text" name="booking_value"> 
<input type="checkbox" name="referral_checked"> <input type="text" name="referral_value"> 
</form> 

我可以用下面的代碼單獨做到這一點:

$("#form input[type=checkbox]").each(function() { 
$(this).change(function(){ 
    if($(this).is(":checked")) { 
    $(this).next().attr("disabled", false); 
    } else { 
    $(this).next().attr("disabled", true); 
    } 
}) 
}) 
+0

你的代碼的工作,這是什麼問題? – xdazz

回答

2

爲了最小化DOM對象的選擇,在像跨度出頭蓋輸入。

這裏你可以看到這個例子:http://jsfiddle.net/g4mQR/

<form id="form"> 
    <span> 
    <input type="checkbox" name="deposit_checked"> 
    <input type="text" name="deposit_value"> 
    </span> 
    <span> 
    <input type="checkbox" name="booking_checked"> 
    <input type="text" name="booking_value"> 
    </span> 
    <span> 
    <input type="checkbox" name="referral_checked"> 
    <input type="text" name="referral_value"> 
    </span> 
</form> 

JS代碼

$('#form input[type=checkbox]').click(function(){ 
    var obj = $(this).siblings('input[type=text]'); 
    obj.attr('disabled', !obj.attr('disabled')); 
}) 
3

您爲disabled屬性設置了錯誤的值。這裏是修復:

$("#form input[type=checkbox]").each(function() { 
$(this).change(function(){ 
    if($(this).is(":checked")) { 
    $(this).next().removeAttr("disabled"); 
    } else { 
    $(this).next().attr("disabled", "disabled"); 
    } 
}) 
}) 

這是在jsfiddle的工作示例。請注意,所有的javascript應該在$(window).load()處理程序中聲明。

+0

jsut試過你suggesstion ..它仍然無法正常工作 – tonoslfx

+0

請參閱jsfiddle的工作示例更新後的帖子。 – Andrei

1

這應該這樣做:

$('#form input[type="checkbox"]').change(function() { 
    var t = $(this); 
    t.next().attr('disabled', ! t.is(':checked')); 
}); 

記得設置在一開始場和複選框狀態。例如:所有未選中和禁用。

+您可能需要更改選擇器中的#form位。

1

我想你想隱藏ñ顯示texbox各自到其對應的複選框,這樣你就可以通過將改變事件做到這一點,這是它是如何做: change事件處理程序被觸發每次複選框的值被改變

$(document).ready(function() { 
    $('.chkboxClass').bind('change', function() { 

    if ($(this).is(':checked')) 
    $(this).next('.txtboxclass').hide(); 
    else 
    $(this).next('.txtboxclass').show(); 

    }); 
}); 

其中.chkboxclass是類所有複選框後.txtboxclass是類的所有文本框

相關問題