Javascript + = equivalent?

My code is a simple function that checks which switch has been pressed and adds the value of this switch to my var input = 0; . However, I know that I am doing something wrong, as it works, but the result is incorrect. When one of the if is true, instead of typing (0) now equal to itself plus the new value getElementById("small").value , it prints 010 as opposed to now 10 .

I know that in Java there is a convention like input += getElementById("small").value; but this does not seem to work. So, as you can see in my example below, I tried the alternative input = input + /*code*/; but still no luck.

I am new to JavaScript, but very familiar with Java. I assume that I'm just using the wrong syntax here, but all of my Google searches are a bust.

 function calculate() { var input = 0; if (document.getElementById("small").checked) { input = input + document.getElementById("small").value; } else if (document.getElementById("medium").checked) { input = input + document.getElementById("medium").value; } else if (document.getElementById("large").checked) { input = input + document.getElementById("large").value; } else { alert("failed"); } document.getElementById("outar").innerHTML = input; } 
+5
source share
6 answers

You are trying to do arithmetic with a string. You must use parseInt() for each of your document.getElementById("....").value expressions because the .value property is a string.

Example:

 input += parseInt(document.getElementById("small").value); 
+5
source

By default, the value is not a number, it is a string. First you have to parse it:

 input += parseInt(document.getElementById("large").value); 
+2
source

You can add an extra + character to the string value to convert it to a number:

 input += +document.getElementById("large").value; 
+2
source

You need to convert .value to a number as an integer or a float with parseInt or parseFloat . .value is a string.

+1
source

Javascript is a dynamically typed language, not a static one, such as java. document.getElementById ("small"). value returns a string to be converted to int using parseInt ().

Ho [e, which helps :)

+1
source

You can also refer to this link-

The return value from the value is a string. You must convert it to int before performing any arithmetic operations.

JavaScript is a dynamically typed language, and not static, such as java.

Return value : a string representing the value of the text field

+1
source

Source: https://habr.com/ru/post/1235651/


All Articles