[英]jQuery checkbox to enable/disable text input and add/remove default value
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. 我正在尝试创建一个小的可重用函数,当选中该函数时,将禁用文本字段并插入默认值“160”,如果未选中,则启用该字段并删除该值。 I have it mostly finished but the unchecking part is throwing me off. 我已经完成了它,但是未检查的部分让我失望了。
$('#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/bwgsA Thanks for any help you can provide! 我把它设置为一个可重用的函数,传递给它的参数,但这给了我更多的麻烦,我希望参数是复选框,目标和值,最好链接到我当前的代码: http : //codepen.io/AlexBezuska / pen / bwgsA感谢您提供的任何帮助!
Working jsFiddle Demo 工作jsFiddle演示
.is(':checked')
. 使用.is(':checked')
。 ==
. 您必须将两个值与==
进行比较。 disabled
, it's better to use .prop()
method instead of .attr()
. 当您使用像disabled
这样的属性时,最好使用.prop()
方法而不是.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: 参考文献:
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');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.