2011-10-19 75 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是类的所有文本框

相关问题