[英]how can i get value of multiple checked box and perform increment using value from checked box
i can's seem to get the element by using id with query selector.我似乎可以通过使用带有查询选择器的 id 来获取元素。 Is there a way to check if the checkbox were checked using document.getelementbyId?
有没有办法检查是否使用 document.getelementbyId 检查了复选框?
<script>
function checked(a,b,c){
var marked = (a+b+c)
document.write(marked);
}
function filled(){
var value1 = document.querySelector("#1:checked").value;
var value2 = document.querySelector("#2:checked").value;
var value3 = document.querySelector("#3:checked").value;
checked(value1,value2,value3);
}
<body>
<input class="chk1" id="1" type="checkbox" value="10"/>
<input class="chk2" id="2" type="checkbox" value="20"/>
<input class="chk3" id="3" type="checkbox" value="30"/>
<button name="submit" onclick="filled()" type="button" style="width: 100px; height: 100px;" >Submit</button>
</body>
Your IDs aren't valid.您的 ID 无效。 Even if they were (such as if you changed them to start with a letter), if a checkbox isn't checked, the
querySelector
will return null
(so accessing the .value
won't work).即使它们是(例如,如果您将它们更改为以字母开头),如果未选中复选框,则
querySelector
将返回null
(因此无法访问.value
)。
Remove the IDs and use querySelectorAll
instead.删除 ID 并改用
querySelectorAll
。 To make things concise, I'd give them all a single class and then the :checked
pseudo-selector combined with the class will select all checked boxes.为了使事情简洁,我会给他们一个 class 然后
:checked
伪选择器与 class 结合将 select 所有复选框。
You should also really avoid inline handlers if at all possible, they have they have way too many problems to be worth using nowadays.如果可能的话,您还应该真正避免使用内联处理程序,它们现在有太多问题值得使用。
document.querySelector('button').addEventListener('click', () => { const checkedBoxes = document.querySelectorAll('.chk:checked'); const sum = [...checkedBoxes].reduce((a, b) => a + Number(b.value), 0); console.log(sum); });
button { width: 100px; height: 100px; }
<input class="chk" type="checkbox" value="10"> <input class="chk" type="checkbox" value="20"> <input class="chk" type="checkbox" value="30"> <button>Submit</button>
using numbers, punctuation or special characters in the value of an ID may cause trouble in other contexts (eg, CSS, JavaScript, regex).在 ID 的值中使用数字、标点符号或特殊字符可能会在其他上下文中引起问题(例如,CSS、JavaScript、正则表达式)。
For example, the following ID is valid in HTML5:例如,以下 ID 在 HTML5 中有效:
<div id="1"> ... </div>
However, it is invalid in CSS because selectors cannot be a digit or start with a digit but can be inbetween or end with a digit.但是,它在 CSS 中无效,因为选择器不能是数字或以数字开头,但可以介于中间或以数字结尾。
So just change the values of your ID attributes in your html and where u referenced them in your javascript.因此,只需更改 html 中的 ID 属性值,以及您在 javascript 中引用它们的位置。 Be sure to not miss any semi colons
一定不要错过任何分号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.