简体   繁体   中英

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.

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>

var radioButtons = document.querySelectorAll("input[type='radio']");
for(var i = 0; i< radioButtons.length; i++)
{
    radioButtons[i].addEventListener("click", (e)=>{
        var radioButton = e.target || e.srcElement;
        var label = document.querySelector("label[for='" + radioButton.id + "'");
        alert(label.innerText.trim());
    });
}

EDIT: Removed the jquery snippet that I initially added. As the user is looking only for a javascript solution, retaining that alone.

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