Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

javascript - 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);
        
         }        
}
question from:https://stackoverflow.com/questions/65953079/why-cant-get-input-value-checkbox-in-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...