简体   繁体   English

Javascript在复选框勾选上启用文本字段

[英]Javascript enable textfield on checkbox tick

I have this HTML Code: 我有这个HTML代码:

<input type="checkbox" onclick="document.getElementById('directory_entry_name').disabled=this.checked;" name="directory_entry" id="directory_entry" />

<strong>Name: </strong><input type="text" name="directory_entry_name" id="directory_entry_name" disabled="disabled" />

The text box is disabled and Im trying to make it so when the checkbox is checked it will enable the text box, and when it is unchecked again it will disable the text box. 文本框被禁用,我试图这样做,当复选框被选中时,它将启用文本框,当它再次被取消选中时,它将禁用文本框。

It works if I use: 如果我使用它可以工作:

<input type="checkbox" onclick="document.getElementById('directory_entry_name').disabled=false;" name="directory_entry" id="directory_entry" />

But then when it is unchecked it doesnt re-disable the textbox. 但是当它未经检查时,它不会重新禁用文本框。

It's reversed. 这是相反的。 Put a ! 放一个! (not) in there. (不)在那里。

document.getElementById('directory_entry_name').disabled=!this.checked;

Browser checks if there is attribute disabled, not the value: disabled attribute description So in function to disable or enable the input you should add and delete "disabled" attribute. 浏览器检查是否有属性已禁用,而不是值: 禁用属性说明因此,在禁用或启用输入的功能中,您应添加和删除“已禁用”属性。 You can do this with jQuery .removeAttr() and .attr() 你可以用jQuery .removeAttr()和.attr()来做到这一点。

so the function will look like this: 所以函数看起来像这样:

function SetInputActive(checkbox) {
if($(checkbox).is(':checked')) $('directory_entry_name').removeAttr("disabled");
else $('directory_entry_name').attr("disabled", "disabled");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM