简体   繁体   中英

How to Grab the Value of a label for a checkbox in pure Javascript

Hello I am inquiring assistance on how to grab the value of a Element corresponding to its element using plain Javascript. My HTML:

<label id ="label1" for = "vanilla">Vanilla
                <input type ="checkbox" id = "vanilla" name = "icecream">
</label><br>
<label id = "label2" for = "chocolate"> chocolate
                <input type = "checkbox" id = "chocolate" name = "icecream">
</label><br>
<label id = "label3" for = "coffee"> Coffee
                <input type = "checkbox" id = "coffee" name = "icecream">
</label> 

My Javascript, Which currently returns either 'Null' or a BlankSpace:

var IceCreamBox = document.getElementsByName("icecream");
    var RootBeerBox = document.getElementsByName("rootbeers");
    var t;
    var j = [];
    for( var i = 0; i < IceCreamBox.length; i++)
    {
        if(IceCreamBox[i].checked == true)
        {
            
            j[i] = IceCreamBox[i].nodeValue;
        }

You could use filter to keep only the checked ones, map and document.querySelector to find their corresponding label:

 // Convert the HTMLCollection to an Array to be able to use forEach, filter, map var IceCreamBox = [...document.getElementsByName("icecream")]; IceCreamBox.forEach(cb => cb.addEventListener('click', listCheckedOptions)); function listCheckedOptions() { var j = IceCreamBox // Filter to keep only the checked ones .filter(cb => cb.checked) // Map them to their label text .map(cb => document.querySelector(`label[for="${cb.id}"]`).textContent.trim()); console.log(j); }
 <label for="vanilla">Vanilla <input type ="checkbox" id="vanilla" name="icecream"> </label><br> <label for="chocolate">Chocolate <input type="checkbox" id="chocolate" name="icecream"> </label><br> <label for="coffee">Coffee <input type="checkbox" id="coffee" name="icecream"> </label>

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