0

I am a beginner at HTML/CCS/Javascript, and I am designing a website which looks like this :

enter image description here

I would like to ensure that the table displayed below is always in sync with the number input element.

I have an input number element like this:

  <label for="loansize">Loan Size (USD) (between 500 and 3000):</label>
  <input type="number" id="loansize" name="loansize" value="3000" min="500" max="3000">

Currently the table does refresh when the user clicks elsewhere on the page, because I have added code like this :

'<div onChange="processPage();">'  ... Render the HTML ... '</div>';

But this does not catch the user being in the process of changing the input number, so I get in a situation like this:

enter image description here

The bottom table remains unchanged from the above picture, even though the number input has changed. It takes a click elsewhere on the page for the table to be back in sync.

How can I ensure the table is re-rendered (i.e. remains in sync) in such a situation ?

user3203476
  • 499
  • 3
  • 12
  • 1
    There are a lot of events you should look out depending on what you expect. `change`, `input`, `keyup`, `blur`, etc... Al those have their specific response to specific dev need. The list is [here](https://developer.mozilla.org/en-US/docs/Web/Events#event_listing). – Louys Patrice Bessette Feb 20 '22 at 06:43
  • 1
    As the two answers below are saying, `input` probably is what you need. Now how to implement it is a bit too wide at this point. – Louys Patrice Bessette Feb 20 '22 at 06:48

2 Answers2

1

Instead of using inline onChange which is considered as a bad practice. You can modify the element using DOM. Here is the simple way to fire the processPage() function every time the value in the loan input is changed.

const loanSize = document.getElementById('loansize');
loanSize.addEventListener('input', processPage);

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event

amlxv
  • 1,610
  • 1
  • 11
  • 18
  • You are quoting a 10 years old answer. I would not say "bad practice" now for the use of an inline event listener attribute. I would say "discouraged" practice. -- In some cases, it still can be ok. – Louys Patrice Bessette Feb 20 '22 at 06:58
  • Thank you for reminding me. I'll use "discouraged" instead later on. – amlxv Feb 20 '22 at 12:07
1

You can try using the onInput listener.

From MDN:

The input event is fired every time the value of the element changes. This is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like.

rrmesquita
  • 466
  • 1
  • 5
  • 15
  • `oninput` is an attribute to set a `input` event callback on page load, while parsing a HTML markup. A listener is a function registered to respond to an event. -- Just quoting a MDN link is not an answer. – Louys Patrice Bessette Feb 20 '22 at 06:54