0

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);
        
         }        
}

1 Answer 1

1
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/

Sign up to request clarification or add additional context in comments.

5 Comments

But then i get , array.push(checkboxnewdivss[i].value) not defined?
Typo - checkboxnewdivss should be checkboxnewdivs
Actually you have several typos. Always check the error console.
Right, the next problem is you haven't defined array anywhere. This is plainly clear by the error that gets generated, array is not defined in the console. See edit.
How in yours exsample jsfiddle get value.., divone from input 1, divtwo from input 2, divthree from input 3 if is checked, and add in div_new innerHTML?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.