简体   繁体   中英

How to enable/disable text field on radio button interaction?

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.

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 an id and using document.getElementById again instead.

If you want to continue using the name attribute, you will have to use document.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:

document.getElementsByName(lineid)[0].disabled = true;

You can see a working version (I think this is how you wanted it anyway) here . And here is a version using getElementsByName .

You are missing a closing brace on the function:

function disablefield(lineid){ 
if (document.getElementById(lineid).checked == true){ 
document.dupedit.lineid='enabled';
}else{ 
document.dupedit.lineid='disabled';
} 
} //<-- here

Also, can I suggest you pass this to the function. Then you don't have to call getElementById

<input onclick='disablefield(this)' type.....

function disablefield(obj){ 
    if (obj.checked == true){ 
        document.dupedit.lineid='enabled';
    }else{ 
        document.dupedit.lineid='disabled';
    } 
} 

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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