简体   繁体   中英

Enabling and disabling checkboxes with javascript

I have been trying to figure out the solution to my problem for a few hours now. I'm still fairly new to Javascript, so please forgive me if I sound stupid. Sadly I don't know jQuery and I'm starting to think that it's inhibiting me to come up with a solution.

What I am trying to do is have a check box that enables disabled radio buttons. If that makes sense.

Example:

  • Choice 1
  • sub choice
  • sub choice
  • sub choice

I would like to be able to click the first checkbox (Choice 1) to enable the sub choices. If it's not clicked, the sub choices should be disabled. :-)

Here is what I've got so far:

<script>
function enableRadios(x) {
    var formElement = eval("checkbox" + x)
    if (formElement[0].disabled) {
        formElement[0].disabled = false
        formElement[1].disabled = false
    } else {
        formElement[0].disabled = true
        formElement[1].disabled = true
    }
 }</script>

<body><input type="checkbox" name="main" value="main" onClick="enableRadios(x)">
<input disabled type="radio" value="1" name="x">
<input disabled type="radio" value="2" name="x">
<input disabled type="radio" value="3" name="x">
<input disabled type="radio" value="4" name="x">
<input disabled type="radio" value="5" name="x">
<input disabled type="radio" value="6" name="x"></body>

I really appreciate your help!

You need to pass a string containing the radio name 'x' , not pass a variable x :

<script>
function toggleRadios(name) {
    var elems = document.getElementsByName(name);
    for(i=0; i<elems.length; i++) {
        elems[i].disabled = !elems[i].disabled;
    }
}
</script>

<input type="checkbox" name="main" value="main" onclick="toggleRadios('x')">
<input disabled type="radio" value="1" name="x">
<input disabled type="radio" value="2" name="x">
<input disabled type="radio" value="3" name="x">
<input disabled type="radio" value="4" name="x">
<input disabled type="radio" value="5" name="x">
<input disabled type="radio" value="6" name="x">

http://jsfiddle.net/samliew/B6tF7/

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