Why the numbers are not adding?

Hi here is two input field with type=“number” and I am also inserting numbers too but the results is concatenating of two fields data instead of adding? I am New to JS. Can you help me why this is happening?

    <input type="number" placeholder="Type number1" id="number1">
	<input type="number" placeholder="Type number2..." id="number2">
    <button type="button" onclick="getInputValue();">Get Value</button>
    
    <script>
        function getInputValue(){
            // Selecting the input element and get its value 
            var inputVal2 = document.getElementById("number1").value;
			var inputVal3 = document.getElementById("number2").value;
			var sum = inputVal2 + inputVal3;
            
            // Displaying the value
            alert(sum);
        }
    </script>

Form input values are considered as text. When you ask JS to “add” two text values, it concatenates them. To get JS to perform an addition, you need to parse the text values as numbers. The function parseFloat can be used to convert a text value to a number; you can use it in your getInputValue function like so:

function getInputValue(){
    // Selecting the input element and get its value 
    var inputVal2 = parseFloat(document.getElementById("number1").value);
    var inputVal3 = parseFloat(document.getElementById("number2").value);
    var sum = inputVal2 + inputVal3;
            
    // Displaying the value
    alert(sum);
}

In this example your inputs will be fairly safe as you’re specifying that the fields are numeric. In other circumstances you may want to check the return value of parseFloat before trying to add them; the function will return NaN if its input cannot be parsed to a number.

Sponsor our Newsletter | Privacy Policy | Terms of Service