简体   繁体   中英

Disable radio buttons on selecting another one

From the below example. there are 2 main radio buttons (opt1 and opt2). opt1 has 3 sub radio buttons. What i need to do is when opt1 is selected nothing should happen but when opt2 is selected, the radio buttons named "main_sub" should be unchecked. How to achieve this.

Code:

<div class="field">
                  <label>Radio button
                 </label>
                  <table width="60%" border="0" cellspacing="0" height="100%" cellpadding="0">
                    <tr>
                      <td><input type="radio" name="main"  id="main" value="Yes" />
                    Opt1 </td>
                    </tr>
                    <tr>
                      <td id="show"  style="padding-left:25px; width:200px; padding-top:5px;  line-height:20px;"><input type="radio" name="main_sub" id="main_sub" value=""  />
                        sub Opt1<br>
                        <input type="radio" name="main_sub"  id="main_sub" value=""  />
                        sub Opt2<br>
                        <input type="radio" name="main_sub"  id="main_sub" value=""  />
                        sub Opt2<br>
                      </td>
                    </tr>
                  </table>

                  <table align="center"  width="100%" border="0" cellspacing="0" height="100%" cellpadding="0">
                    <tr>
                      <td align="center" style="padding-right:60px;" ><input type="radio" name="main"  id="main" value="No" />
                        Opt2</td>
                    </tr>
                  </table>
                </div>

First, ids must be unique so change your 2nd main radio id to main2

After that you can do this to achieve what you want

document.getElementById("main2").addEventListener("change", function(){
    if (this.checked) {
        var subs_list = document.getElementsByName("main_sub");
        var subs = Array.prototype.slice.call(subs_list);
        console.log(subs);
        subs.forEach(function(sub){
            sub.checked = false;
        });
    }
});

FIDDLE


EDIT

And i guess you may want the opposite way. If you click on a sub radio, main1 should be checked if it's already not and main2 should be unchecked. For this you need to add this code too.

var subs_list_2 = document.getElementsByName("main_sub");
var subs_2 = Array.prototype.slice.call(subs_list_2);
subs_2.forEach(function(sub){
    sub.addEventListener("change", function(){
        if (this.checked) {
            document.getElementById("main2").checked = false;
            document.getElementById("main").checked = true;
        }
    });
});

UPDATED FIDDLE

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