javascript 用于启用/禁用文本输入和添加/删除默认值的 jQuery 复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16806830/
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
jQuery checkbox to enable/disable text input and add/remove default value
提问by glasses
I am trying to create a small reusable function that will, when checked, disable a text field and insert a default value of '160', and when unchecked, enable the field and remove the value. I have it mostly finished but the unchecking part is throwing me off.
我正在尝试创建一个小的可重用函数,该函数在选中时将禁用文本字段并插入默认值“160”,如果未选中,则启用该字段并删除该值。我已经完成了大部分,但取消检查的部分让我失望。
$('#chkIsTeamLead').change(function(){
if ($('#chkIsTeamLead').checked = true){
$('#txtNumHours').val('160').attr('disabled', 'disabled');
console.log('checked');
}
if ($('#chkIsTeamLead').checked = false){
$('#txtNumHours').val('').removeAttr('disabled');
console.log('unchecked');
}
});
I had it setup as a reusable function with arguments passed to it but that was giving me more trouble, I would like the arguments to be checkbox, target, and value preferably link to my current code: http://codepen.io/AlexBezuska/pen/bwgsAThanks for any help you can provide!
我将它设置为一个可重用的函数,参数传递给它,但这给我带来了更多麻烦,我希望参数是复选框、目标和值,最好链接到我当前的代码:http: //codepen.io/AlexBezuska /pen/bwgsA感谢您提供的任何帮助!
回答by
- Use
.is(':checked'). - You must compare two values with
==. - When you are working with attribute like
disabled, it's better to use.prop()method instead of.attr().
- 使用
.is(':checked'). - 您必须使用 比较两个值
==。 - 当您使用类似 的属性时
disabled,最好使用.prop()method 而不是.attr()。
$('#chkIsTeamLead').change(function(){
if ($('#chkIsTeamLead').is(':checked') == true){
$('#txtNumHours').val('160').prop('disabled', true);
console.log('checked');
} else {
$('#txtNumHours').val('').prop('disabled', false);
console.log('unchecked');
}
});
References:
参考:
回答by Mayank Awasthi
try this
试试这个
$('#chkIsTeamLead').change(function(){
if ($('#chkIsTeamLead').is(':checked')){
$('#txtNumHours').val('160').attr('disabled', 'disabled');
console.log('checked');
} else {
$('#txtNumHours').val('');
$('#txtNumHours').removeAttr('disabled');
console.log('unchecked');
}
});

