0

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.

3
  • 1
    document.querySelector could return null if its not found or checked which will throw Commented Jul 1, 2022 at 19:46
  • 1
    selector would NOT have a value. You would be adding two strings together. Commented Jul 1, 2022 at 19:49
  • const total = +(select?.value || 0) + +(selecto?.value || 0) Commented Jul 1, 2022 at 19:49

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Then It does not count the value it returns 20202
Ah so the reason when I tried to paseInt the value was because I console logged selector.value, Thanks alot for your answer!
1

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

1 Comment

Thanks for your answer aswell, now I dont have to write them all out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.