Skip to content Skip to sidebar Skip to footer

Javascript On Input Field Addition

I am giving values to input fields its adding concatination but not adding please verify it on input function is correct or wrong once verify then reply me thats it my question.

Solution 1:

You have strings, that is why it is concatenating. Make integers with: http://www.w3schools.com/jsref/jsref_parseint.asp

And it will work well.

Solution 2:

First, when you read values from DOM, they are read as string. You will have to use parseInt or parseFloat to convert string to integer.

Second, + operator has a override function for string to act as concatenation operator.

Also notice, I have used .value || 0. Here if value does not exist, performing arithmetic operation over it will return NaN so adding default value (0).

//// JavaScript function to add input values display into another input field functioncalculate() {
  var x = document.getElementById('fee_selector_holder').value || 0;
  var y = document.getElementById('content').value || 0;
  var result = document.getElementById('result');
  var myResult = parseInt(x) + parseInt(y);
  result.value = myResult;

}
<inputtype="text"name="hostelfees"id="content"oninput="calculate()"><inputtype="text"name="fee_id"id="fee_selector_holder"oninput="calculate()"><inputtype="text"id="result"name="totalfee">

Solution 3:

You have to parse the input values to integer as all input values are string by default:

//// JavaScript function to add input values display into another input field functioncalculate() {
  var x = document.getElementById('fee_selector_holder').value || 0; // default value 0 if input is blankvar y = document.getElementById('content').value || 0; // default value 0 if input is blankvar result = document.getElementById('result');
  var myResult = parseInt(x, 10) + parseInt(y, 10); // parse it here 
  result.value = myResult;

}
<inputtype="text"name="hostelfees"id="content"oninput="calculate()"><inputtype="text"name="fee_id"id="fee_selector_holder"oninput="calculate()"><inputtype="text"id="result"name="totalfee">

Solution 4:

You should add attribute to result

result.setAttribute("value", myResult);

Post a Comment for "Javascript On Input Field Addition"