无法计数JavaScript中的形式值

发布于 2025-02-12 06:33:24 字数 600 浏览 2 评论 0原文

我得到了一个具有编号值的输入

<input type="radio" id="ja" name="upprepas" value="0">
<input type="radio" id="ja" name="bekanta" value="2">

,但我也有其他10个输入,我想计算所有输入的值。所以我尝试了一下:

var select = document.querySelector('input[name="upprepas"]:checked');
console.log(select.value);
var selecto = document.querySelector('input[name="bekanta"]:checked');
console.log(selecto.value);
var selector = select.value + selecto.value;
console.log(selector.value);

但是选择器总是不确定的,为什么?我认为这可能是一个字符串,而不是整数,所以我尝试在select.value之前放置parseint,但它不起作用。

I got a input like this with a numbered value

<input type="radio" id="ja" name="upprepas" value="0">
<input type="radio" id="ja" name="bekanta" value="2">

But i also have like 10 other inputs, I want to count all of the inputed values. So I tried this:

var select = document.querySelector('input[name="upprepas"]:checked');
console.log(select.value);
var selecto = document.querySelector('input[name="bekanta"]:checked');
console.log(selecto.value);
var selector = select.value + selecto.value;
console.log(selector.value);

But selector is always undefined, why is that? I thought that it maybe was a string and not an integer so I tried putting parseInt before select.value but it didn't work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一指流沙 2025-02-19 06:33:27

您始终可以使用 querySelectorall 查找所有检查收音机,并循环循环并添加它们。

let checked = document.querySelectorAll("input[type='radio']:checked");
let total = 0;
checked.forEach(function(e){
   total += parseInt(e.value);
});

console.log(total)
<input type="radio" name="kreativxt" value="10"> A
<input checked type="radio" name="krexativt" value="1"> V
<input checked type="radio" name="krewativt" value="2"> C

You can always use querySelectorAll to find all of the checked radios, and loop through their values and add them up.

let checked = document.querySelectorAll("input[type='radio']:checked");
let total = 0;
checked.forEach(function(e){
   total += parseInt(e.value);
});

console.log(total)
<input type="radio" name="kreativxt" value="10"> A
<input checked type="radio" name="krexativt" value="1"> V
<input checked type="radio" name="krewativt" value="2"> C

感情旳空白 2025-02-19 06:33:26

您需要做的是替换var selector = select.value + selecto.value; at var selector = parseint(select.value) + parseint(selecto.value); 还使用const而不是var,这是最佳练习^^

What you would need to do is replace var selector = select.value + selecto.value; with var selector = parseInt(select.value) + parseInt(selecto.value); Also use const or let instead of var, it's a best practice ^^

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文