简体   繁体   English

获取复选框选择的值

[英]get checkbox selected value

I have multiple checkboxes that get generated by a php code and the HTML looks like this: 我有多个由php代码生成的复选框,HTML如下所示:

<input name="checkbox" id="checkbox" value="firstBox" type="checkbox">
<input name="checkbox" id="checkbox" value="secondBox" type="checkbox">

However when I try to get the selected value by the user using below script 但是,当我尝试使用以下脚本由用户获取选定的值时

document.getElementById('checkbox').value

I always get 'firstBox' even when the secondBox is selected. 即使选择了secondBox,我也总是得到“ firstBox”。 Please help me solving this 请帮我解决这个问题

IDs are identifiers for specific elements. ID是特定元素的标识符。 Therefore, they must be unique. 因此,它们必须是唯一的。

An alternative is setting the same name and use the function querySelectorAll to get the checked checkboxes. 另一种方法是设置相同的名称,然后使用功能querySelectorAll获取选中的复选框。

Use this selector to get the checked options: [name="checkbox"]:checked 使用此选择器获取选中的选项: [name="checkbox"]:checked

 document.querySelector('#check').addEventListener('click', function() { var checked = Array.from(document.querySelectorAll('[name="checkbox"]:checked')); checked.forEach(function(e) { console.log(e.value); }); }); 
 <input name="checkbox" name="checkbox" value="firstBox" type="checkbox"> <input name="checkbox" name="checkbox" value="secondBox" type="checkbox"> <button id='check'>Check</button> 

IDs must be unique. ID必须是唯一的。

<input name="checkbox" id="checkbox1" value="firstBox" type="checkbox">
<input name="checkbox" id="checkbox2" value="secondBox" type="checkbox">

Get value of first checkbox: 获取第一个复选框的值:

document.getElementById('checkbox1').value

Get value of second checkbox 获取第二个复选框的值

document.getElementById('checkbox2').value       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM