Jack the man
Jack the man

Reputation: 31

Unable to count form value in javascript

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.

Upvotes: 0

Views: 39

Answers (2)

ShackER
ShackER

Reputation: 96

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 ^^

Upvotes: 3

imvain2
imvain2

Reputation: 15867

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

Upvotes: 1

Related Questions