Search code examples
javascripthtmldhtml

How to have a radio button select another radio button's value


I was wondering if there is a way to make a radio button select another radio buttons data. For example, a "select all" radio button, would select another radio button. Or In the event of a survey where a question could be rated from 0 to 5, when "select all as 0" is selected, all the following radio buttons are selected at "0". I feel like there is an easy way of doing this, but I have no Idea what it would be (possibly javascript?) Thanks!


Solution

  • HTML

    <button type='button' onclick='selectAs0()'>Select All As 0</button>
    
    <input type='radio' name='setA' value='0' /> 0
    <input type='radio' name='setA' value='1' /> 1
    
    <input type='radio' name='setB' value='0' /> 0
    <input type='radio' name='setB' value='1' /> 1
    

    JS

    function selectAs0() {
      var ALL = document.getElementsByTagName("INPUT");
    
      for(var x = 0; x< ALL.length;x++) {
        if(ALL[x].type=='radio' && ALL[x].value == 0) {
          ALL[x].checked = true;
        }
      }
    }
    

    Untested at this point but should work-ish.

    // EDIT

    If you're determined to use a radio button to actuate the function, the same concept will work...

    <input type='radio' onclick='selectAs0()' />
    

    ...but you'll have to add extra code to de-check the radio once it's already selected.