[英]checkbox disable/enable inquiry using javascript function
I'm fairly new to JavaScript and I have been Googling all day for this but I only found how to enable and disable one textbox using one checkbox. 我对JavaScript相当陌生,为此我整天都在搜寻Google,但是我只发现了如何使用一个复选框启用和禁用一个文本框。 I tweaked the code a bit to work with what I want and here is what I got.
我对代码进行了一些调整,以实现所需的功能,这就是我所得到的。 I'm thinking of instructing JS function to follow only the id of the checkbox, but I can't seem to figure out how to do it.
我正在考虑指示JS函数仅遵循复选框的ID,但似乎无法弄清楚该怎么做。
Here is my code: 这是我的代码:
JavaScript 的JavaScript
<script>
function enableText(checked){
if(!checked){
document.getElementById('sel1').disabled = true;
document.getElementById('txt1').disabled = false;
}
else{
document.getElementById('sel1').disabled = false;
document.getElementById('txt1').disabled = true;
}
}
function enableText(checked){
if(!checked){
document.getElementById('sel2').disabled = true;
document.getElementById('txt2').disabled = false;
}
else{
document.getElementById('sel2').disabled = false;
document.getElementById('txt2').disabled = true;
}
}
</script>
HTML 的HTML
<form name=sr2 method=post>
<select name="pt" id="sel1">
<option>test</option>
</select>
<input type="checkbox" name="cb1" checked="checked" onclick="enableText(this.checked)">
Others
<input type="text" name="pt" id="txt1" disabled="disabled">
<select name="dept" id="sel2">
<option>test</option>
</select>
<input type="checkbox" name="cb2" onclick="enableText(this.checked)" checked="checked">
Others
<input type="text" name="dept" id="txt2" disabled="disabled">
</form>
My question is how can I set the function in js to instruct cb1
to only enable txt1
and disable sel1
and cb2
to only enable txt2
and disable sel2
? 我的问题是如何在js中设置功能以指示
cb1
仅启用txt1
并禁用sel1
和cb2
仅启用txt2
并禁用sel2
? My code works but, for some reason, it enables txt1
and txt2
and disables sel1
and sel2
at the same time. 我的代码有效,但是由于某种原因,它同时启用
txt1
和txt2
并同时禁用sel1
和sel2
。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
You have created two functions with the same name: enableText
. 您已经创建了两个具有相同名称的函数:
enableText
。 Simplifying your code: 简化代码:
function enableText(checked, index){
var sel = true, txt = false;
if(checked) {
sel = false;
txt = true;
}
document.getElementById('sel' + index).disabled = sel;
document.getElementById('txt' + index).disabled = txt;
}
And in your HTML: 在您的HTML中:
onclick="enableText(this.checked, 1)"
And change the 2nd parameter for the next items. 并更改下一个项目的第二个参数。
A second version of your function with ternaries, but with the same purpose: 具有三元数的函数的第二个版本,但具有相同的目的:
function enableText(checked, index) {
document.getElementById('sel' + index).disabled = (checked ? false : true);
document.getElementById('txt' + index).disabled = (checked ? true : false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.