it needs to count the values but its doesnt work javascript

946 views javascript
4

i have made a small code but he needs to count the value + a other value but its not work but he only places everything side by side. its a realy stupid question i know. I just do not see how it should be done.

    <!DOCTYPE html>
<html>
<body>


<form id="first" name="first">
    <input type="radio" name="rads" value="1" />1
    <input type="radio" name="rads" value="2" />2
    <input type="radio" name="rads" value="3" />3
    <input type="radio" name="rads" value="4" />4
</form>
<form id="second" name="second">
    <input type="radio" name="rads" value="1" />1
    <input type="radio" name="rads" value="2" />2
    <input type="radio" name="rads" value="3" />3
    <input type="radio" name="rads" value="4" />4
</form>


<span id="result"></span>
<script>



document.onclick = function hoi(){
 var first = document.first.rads.value;
    var second = document.second.rads.value;


 var all = first + second;
   result.innerHTML =  all;
}

</script>

</body>
</html>

answered question

What have you tried? What is the output you're getting? What exactly is your desired behavior?

3 Answers

2

The value property on a input is string, so there is string concatenation going on, convert both inputs to a number then add:

result.innerHTML = Number(first) + Number(second)

posted this
4

You are trying to add two strings.

When you get value, notice your value is in quotes making it a string. You can parse int from string. You want to add something to handle when only 1 number is selected.

   <!DOCTYPE html>
<html>
<body>


<form id="first" name="first">
    <input type="radio" name="rads" value="1" />1
    <input type="radio" name="rads" value="2" />2
    <input type="radio" name="rads" value="3" />3
    <input type="radio" name="rads" value="4" />4
</form>
<form id="second" name="second">
    <input type="radio" name="rads" value="1" />1
    <input type="radio" name="rads" value="2" />2
    <input type="radio" name="rads" value="3" />3
    <input type="radio" name="rads" value="4" />4
</form>


<span id="result"></span>
<script>



document.onclick = function hoi(){
 var first = document.first.rads.value;
    var second = document.second.rads.value;


 var all = parseInt(first) + parseInt(second);
   result.innerHTML =  all;
}

</script>

</body>
</html>

posted this
9

First of all, welcome to StackOverflow!

The solution to your problem is very simple: The value property returns a string, and using + on strings concatenates them. You first have to convert it to a number using parseInt(), and then add them together which would look like so:

var all = parseInt(first) + parseInt(second);

posted this

Have an answer?

JD

Please login first before posting an answer.