purender
purender

Reputation: 29

javascript on input field addition

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

}
<input type="text" name="hostelfees" id="content" oninput="calculate()">

<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">

<input type="text" id="result" name="totalfee">

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.

Upvotes: 1

Views: 2520

Answers (4)

Michel
Michel

Reputation: 1165

You should add attribute to result

result.setAttribute("value", myResult);

Upvotes: 0

Jai
Jai

Reputation: 74738

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 
function calculate() {
  var x = document.getElementById('fee_selector_holder').value || 0; // default value 0 if input is blank
  var y = document.getElementById('content').value || 0; // default value 0 if input is blank
  var result = document.getElementById('result');
  var myResult = parseInt(x, 10) + parseInt(y, 10); // parse it here 
  result.value = myResult;

}
<input type="text" name="hostelfees" id="content" oninput="calculate()">

<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">

<input type="text" id="result" name="totalfee">

Upvotes: 1

Rajesh
Rajesh

Reputation: 24915

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 
function calculate() {
  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;

}
<input type="text" name="hostelfees" id="content" oninput="calculate()">

<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">

<input type="text" id="result" name="totalfee">

Upvotes: 1

maskacovnik
maskacovnik

Reputation: 3084

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.

Upvotes: 1

Related Questions