Skip to content
Advertisement

How to call methods on input of ‘number’ type?

I’m new to HTML and have an input with type=number:

<input type="number" min="1" value="1" id="amount-input" (click)="chooseStanding(standingspot.priceCategory)">

With (click), chooseStanding(standingspot.priceCategory) will be called every time the up or down button is clicked.

Just for reference

But is it possible to have different method calls based on which button was clicked? For example, if the down button was pressed a different method removeStanding(standingspot.priceCateegory) should be called and if the up button was pressed, chooseStanding(standingspot.priceCategory) should be called. I would really appreciate any help! 🙂

Advertisement

Answer

Similar to Dan’s solution, but taking into consideration the exact difference between the previous and the next value.

Also, there is no need to store the previous value in a variable.

const onIncrement = () => console.log('INCREMENT');
const onDecrement = () => console.log('DECREMENT');
const onChange = value => console.log('CHANGE TO: ', value);

const onChangeNumber = event => {
  const input = event.target;
  const newValue = parseInt(input.value);
  const oldValue = parseInt(input.getAttribute('old-value') || input.defaultValue) || 0;
  input.setAttribute('old-value', input.value);
 
  if (newValue === oldValue + 1)
    onIncrement();
  else
    if (newValue === oldValue - 1)
      onDecrement();
    else
      onChange(newValue);
}
<input type='number' onchange='onChangeNumber(event)' defaultValue="0"/>
Advertisement