javascript 基于 jQuery 中的复选框切换输入的禁用属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13756917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:41:45  来源:igfitidea点击:

Toggle Disabled Attribute on Input Based on Checkbox in jQuery

javascriptjqueryforms

提问by cchiera

I have a checkbox that is unchecked by default and a disabled input by default.

我有一个默认情况下未选中的复选框和默认情况下禁用的输入。

<label class="checkbox span3"><input type="checkbox"> I am a full-time student.</label>
<input class="inputIcon span3" id="disabledInput" type="text" placeholder="Enter School Name" disabled>

I have full control over the class and id names and the site uses jQuery so can use that or plain javascript if needed.

我可以完全控制类和 id 名称,并且该站点使用 jQuery,因此可以在需要时使用该名称或纯 javascript。

If a user checks the box, then the "disabled" attribute should be removed from the following input. If the user unchecks it should become disabled again.

如果用户选中该框,则应从以下输入中删除“禁用”属性。如果用户取消选中它应该再次被禁用。

Found a several similar questions on StackOverflow but none seem to be this exact use case.

在 StackOverflow 上发现了几个类似的问题,但似乎没有一个是这个确切的用例。

回答by Adil

You have to assign id to checkbox to bind the click to particular checkbox,

您必须将 id 分配给复选框以将点击绑定到特定的复选框,

Live Demo

现场演示

<input type="checkbox" id="chk">

$("#chk").click(function(){   
    $("#disabledInput").attr('disabled', !this.checked)
});

回答by Adam Rackis

First give your checkbox an id

首先给你的复选框一个id

<input id='cbFullTime' type="checkbox">

Then in its click handler, fetch the textbox, and set its disabled propertyto the inverse of the current value of the checkbox's checkedproperty:

然后在其单击处理程序中,获取文本框,并将其禁用属性设置为复选框checked属性当前值的倒数:

$('#cbFullTime').click(function() { 
    var cbIsChecked = $(this).prop('checked');
    $('#disabledInput').prop('disabled', !cbIsChecked); 
});


Note that, while using attrand removeAttrwill work (assuming you're not using exactly jQuery 1.6), using the propfunction is a bit simpler, and a bit more correct. For more information, check out this link

请注意,虽然使用attrand removeAttrwill 工作(假设您没有完全使用 jQuery 1.6),但使用该prop函数会更简单一些,也更正确一些。有关更多信息,请查看此链接

回答by Sridhar Narasimhan

Try the below

试试下面的

$(".checkbox").find("checkbox").click(function() { 
$('#disabledInput').prop('disabled', $(this).prop('checked')); 
});