如何启用/禁用单选按钮交互上的文本字段?
无法让它发挥作用。第一次使用传递给函数的变量。取消选中单选按钮应禁用表单字段,反之亦然。 lineid 变量将此无线电/文本输入对与其他 10 个输入对区分开来。
我的代码:
<script type="text/javascript">
function disablefield(lineid){
if (document.getElementById(lineid).checked == true){
document.dupedit.lineid.disabled = false;
} else {
document.dupedit.lineid.disabled = true;
}
}
</script>
我的 HTML 的子集。
Cannot get this to work. First time using variables passed into functions. Unchecking radio button should disable form field and vice versa. lineid variable distinguishes this radio/text input pair from 10 others.
My code:
<script type="text/javascript">
function disablefield(lineid){
if (document.getElementById(lineid).checked == true){
document.dupedit.lineid.disabled = false;
} else {
document.dupedit.lineid.disabled = true;
}
}
</script>
Subset of my HTML.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将一个字符串传递到
disablefield
函数中,因此在传递时将值放在引号中。类似于:这是因为
document.getElementById
需要一个字符串,而不是整数。其次,要启用/禁用该字段,您需要使用
disabled = true;
而不是= 'disabled'
。document.dupedit.lineid
正在查找名称为“lineid”的字段,该字段在您的表单中不存在。我建议为该字段指定一个id
并再次使用document.getElementById
。如果您想继续使用
name
属性,则必须使用document.getElementsByName
。这将返回一个匹配元素的数组(因为多个元素可以共享相同的名称),但如果在您的代码中您知道相关元素是唯一具有该名称的元素,您可以执行以下操作:您可以看到一个工作版本(我想这就是你想要的)这里。 此处是使用
getElementsByName
的版本。You need to pass a string into your
disablefield
function, so put the value in quotes when you pass it in. Something like:<input onclick="disablefield('2671997')" />
This is because
document.getElementById
expects a string, not an integer.Secondly, to enable/disable the field, you need to use
disabled = true;
rather than= 'disabled'
.document.dupedit.lineid
is looking a for a field with name "lineid", which doesn't exist in your form. I would suggest giving the field anid
and usingdocument.getElementById
again instead.If you want to continue using the
name
attribute, you will have to usedocument.getElementsByName
instead. This returns an array of matching elements (since multiple elements can share the same name), but if in your code you know that the element in question is the only one with that name, you can do this:You can see a working version (I think this is how you wanted it anyway) here. And here is a version using
getElementsByName
.您在函数上缺少右大括号:
另外,我可以建议您将
this
传递给该函数吗?那么你就不必调用getElementById
You are missing a closing brace on the function:
Also, can I suggest you pass
this
to the function. Then you don't have to callgetElementById
我认为你需要的是重新思考代码。
请勿在复选框上使用 ID。最好将该 ID 移动到您想要禁用/启用的文本字段,并检查该字段是否已禁用/启用,而不是复选框本身
使用更干净的 JS。
使用
请看一下我为您编译的jsFiddle。它符合你的预期吗,丹?
I think what you need is to re-think the code.
Don't use ID on the checkbox. Better move that ID to the text field you want to disable/enable and check whether that field is disabled/enabled, not the checkbox itself
use cleaner JS.
Please, take a look at the jsFiddle, I have compiled for you. Does it do what you expect, Dan?