对于此页面:
<input type="checkbox" checked id="chk1" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk2" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk3" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk4" onclick="myFunction(this)" />
<input type="text" id="txt1" disabled="disabled" />
<input type="text" id="txt2" disabled="disabled" />
<input type="text" id="txt3" disabled="disabled" />
<input type="text" id="txt4" disabled="disabled" />
<script>
function myFunction(el) {
var txt = document.getElementById(el.id.replace('chk', 'txt'));
if (el.checked) {
document.getElementById(txt).removeAttribute("disabled");
}
else
document.getElementById(txt).setAttribute("disabled", "disabled");
}
</script>
我已经尝试过这个脚本但它的错误是
&#34; Microsoft JScript运行时错误:&#39; document.getElementById(...)&#39;是 null或不是对象&#34;
答案 0 :(得分:0)
您的脚本部分中有错误:
var txt = document.getElementById(el.id.replace('chk', 'txt'));
这会让你回到textbox
的整个元素而不是id。如果你改变它,它应该工作:
<script>
function myFunction(el) {
var txt = el.id.replace('chk', 'txt');
if (el.checked) {
document.getElementById(txt).removeAttribute("disabled");
}
else
document.getElementById(txt).setAttribute("disabled", "disabled");
}
</script>
您可以在此JSFiddle中对其进行测试(请注意,我还删除了小提琴示例中checked
的{{1}}属性)
答案 1 :(得分:0)
具有var txt = el.id.replace('chk', 'txt');
var txt = document.getElementById(el.id.replace('chk', 'txt'));
无需使用document.getElementById
,因为您已在myFunction(this)
使用disabled
true | false
function myFunction(el) {
var txt = el.id.replace('chk', 'txt');
if (el.checked ) {
document.getElementById(txt).disabled = false;
}
else
document.getElementById(txt).disabled = true;
}
<input type="checkbox" checked id="chk1" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk2" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk3" onclick="myFunction(this)" />
<input type="checkbox" checked id="chk4" onclick="myFunction(this)" />
<input type="text" id="txt1" disabled>
<input type="text" id="txt2" disabled>
<input type="text" id="txt3" disabled>
<input type="text" id="txt4" disabled>
答案 2 :(得分:0)
使用此声明,您将看到文本框
var txt = document.getElementById(el.id.replace('chk', 'txt'))
BUt那么你不应该使用这个
document.getElementById(txt).removeAttribute("disabled");
但是这个
txt.removeAttribute("disabled");
例如,请参阅小提琴
答案 3 :(得分:0)
function myFunction(el) {
var txt = document.getElementById(el.id.replace('chk', 'txt'));
if (el.checked) {
txt.removeAttribute("disabled");
}
else
txt.setAttribute("disabled", "disabled");
}
See working demo。如果它仍然不适用于你,只需将你的脚本移动到html标记之上。