Search code examples
javascriptradio-buttonlabel

Assign radio button's label instead of value


Consider the following radio buttons in html:

<tr>  
    <td> Lighting </td>
    <td> <label for="lighting1"> Off </label> 
        <input id = "lighting1" name="lighting" type="radio" value="0"> </td>
    <td> <label for="lighting2"> Low </label> 
        <input id = "lighting2" name="lighting" type="radio" value="1"> </td>
    <td> <label for="lighting3"> High </label> 
        <input id = "lighting3" name="lighting" type="radio" value="2"> </td>
</tr>  

I need a javascript statement that will assign the radio button's label on a variable instead of its value, ie 'Off', 'Low' or 'High' instead of '0', '1' or '2'. when the radio button is checked.

It seems so simple and straightforward yet I fail to achieve it no matter what I try. I haven't found any working answers on the forum either. Please spare me of stating all non workable trials and enlighten me with just a single line of code that works.


Solution

  • You can fetch radios using common name and update values using input.value = newValue

    function updateValues(){
      var radios = document.querySelectorAll('[name="lighting"]');
      for(var i = 0; i< radios.length; i++){
        var id = radios[i].getAttribute('id');
        radios[i].value = document.querySelector('label[for="'+id+'"]').textContent.trim()
      }
    }
    
    function registerEvents(){
      var radios = document.querySelectorAll('[name="lighting"]');
      for(var i = 0; i< radios.length; i++)
        radios[i].addEventListener("change", handleChange)
    }
    
    function handleChange(){
      console.log(this.value)
    }
    
    registerEvents();
    <tr>
      <td> Lighting </td>
      <td> <label for="lighting1"> Off </label>
        <input id="lighting1" name="lighting" type="radio" value="0"> </td>
      <td> <label for="lighting2"> Low </label>
        <input id="lighting2" name="lighting" type="radio" value="1"> </td>
      <td> <label for="lighting3"> High </label>
        <input id="lighting3" name="lighting" type="radio" value="2"> </td>
    </tr>
    
    <p id="selectedValues"></p>
    
    <button onclick="updateValues()" >Update Values</button>