0

https://codepen.io/kev_daddy/pen/MMWEMG

I am building a form that is meant to update the difference between two values in real time (ie without refreshing the page). It is comprised of multiple fields, but ultimately I'll be getting the sum of two values, and displaying this using HTML.

The entire thing appears to work as intended until I get to the function that is meant to display the sum in html.

The intention is that the result (a hidden field) is shown as plain text in output. It doesn't trigger on the onset, however if i punch in an extra character using my keyboard, the event is finally heard and the text shows. up.

I am sure that I am missing something, but how do I ensure that the sum is outputted?

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; }


var input = document.getElementById("result"); 
var output = document.getElementById("output"); input.addEventListener("input", function() {
  output.innerText = this.value;
});
<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">

<hr>

<p>You can earn <span id="output"></span> more!

1 Answer 1

2

There is no input event on span. You can create a separate function and pass the value of the calculation to this function whose responsibility will be to update the span text content

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;
  updateText(myResult)
}

function updateText(val) {
  document.getElementById("output").innerText = val;
}
<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">

<hr>

<p>You can earn <span id="output"></span> more!

Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful! How would you modify the snippet if I want it to rely on just a single field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.