Enabling and disabling checkboxes with javascript

12,104

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/

Share:
12,104

Related videos on Youtube

Sadfsa Asffds
Author by

Sadfsa Asffds

Updated on September 15, 2022

Comments

  • Sadfsa Asffds
    Sadfsa Asffds over 1 year

    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!

  • Sadfsa Asffds
    Sadfsa Asffds almost 11 years
    You are amazing! Thank you so much!
  • naveen
    naveen almost 11 years
    +1: aint it better to pass this.checked as an argument in the toggleRadios function and enable or disable based on that value.