簡體   English   中英

Javascript如何建立一個復選框列表以返回已檢查的值

[英]Javascript How to build a checkbox list that returns the values which have been checked

我正在嘗試構建一個頁面,該頁面將具有對象列表,例如:-obj1 -obj2 -obj3,每個對象都有一個復選框。 我在構建一個函數時會遇到麻煩,該函數將返回所有已檢查框的值。

這是我的代碼,我覺得自己很接近,但無法正常工作:

 function myFunction() { var x = document.getElementById("objs").value; document.getElementById("demo").innerHTML = x; } 
 OBJ1: <input type="checkbox" id="obj1" value="1"> OBJ2: <input type="checkbox" id="obj2" value="2"> OBJ3: <input type="checkbox" id="obj3" value="3"> <p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p> <button onclick="myFunction()">Refresh</button> <p id="demo"></p> 

您可以使用有效的選擇器(而不是無效的“ objs”,因為沒有這樣的元素),使用querySelectorAll來獲取所有選中的復選框:

 function myFunction() { var selected = Array.from(document.querySelectorAll("input[type=checkbox]:checked")) .map(function(checkbox) { return checkbox.value; }) .join(' '); document.getElementById("demo").innerHTML = selected; } 
 OBJ1: <input type="checkbox" id="obj1" value="1"> OBJ2: <input type="checkbox" id="obj2" value="2"> OBJ3: <input type="checkbox" id="obj3" value="3"> <p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p> <button onclick="myFunction()">Refresh</button> <p id="demo"></p> 

可能的解決方案。

 const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const elems = document.querySelectorAll('input[type="checkbox"]:checked'); console.log(Array.from(elems).map(c => c.value)); }) 
 OBJ1: <input type="checkbox" id="obj1" value="1"> OBJ2: <input type="checkbox" id="obj2" value="2"> OBJ3: <input type="checkbox" id="obj3" value="3"> <p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p> <button id='btn'>Refresh</button> <p id="demo"></p> 

不完全確定您要在輸出中尋找什么,但這會為您提供已選中的復選框的值

 function myFunction() { var x = document.getElementsByClassName("objs"); var s=''; for (var i = 0;i<x.length;i++){ if (x[i].checked) s = s + x[i].value; } document.getElementById("demo").innerHTML = s; } 
 OBJ1: <input type="checkbox" class="objs" value="1"> OBJ2: <input type="checkbox" class="objs" value="2"> OBJ3: <input type="checkbox" class="objs" value="3"> <p>Click the "Try it" button to display the value of the value attribute of the checkbox.</p> <button onclick="myFunction()">Refresh</button> <p id="demo"></p> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM