Search code examples
javascriptarraysinputcheckboxreturn-value

Why can't get input value checkbox in array?


In the code described below, the value of the input should be taken from everyone in the array and a new div with the input value in innerHtml should be created. I don't know why get an error that length.value not defined?

<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divsone">
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divstwo">
<input type="checkbox" class="checkboxnewdivs" id="checkboxnewdivs" name="checkboxnewdivs" value="divsthree">

<button onclick="myFunction()">Click me</button>

<div id="container"></div>

function myFunction() {
let array = [];
var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked');

         for (var i = 0; i < checkboxnewdivs.length; i++) {
                     
         var iddivs = array.push(checkboxnewdivs[i].value);  
         
         var div_new = document.createElement("DIV"); 
         div_new.innerHTML = "ID div:"+iddivs ;                   
         document.getElementById("container").appendChild(div_new);
        
         }        
}

Solution

  • var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked').value;
    

    Should be

    var checkboxnewdivs = document.querySelectorAll('input[name="checkboxnewdivs"]:checked');
    

    The first one is trying to get a value property from a node collection, which will obviously be undefined.

    You also had some typos (double 's') and don't define array anywhere. Define that where you defined checkboxnewdivs.

    Working demo: https://jsfiddle.net/mitya33/m9L2dvz5/1/