skip to Main Content

Is it possible to detect when the stepper arrows are clicked in an HTML number input? My inputs are arbitrary size decimals, so I have an attribute step=0.00000001 to have a valid <input type=number>. However, the stepper arrows should increase/decrease by 0.01. So if a function can be called when those arrows are clicked, I can programmatically increase/decrease the input.

3

Answers


  1. You just need to use the onChange function:

    <input type="number" step="0.00000001" onChange="alert('change')" />
    

    Edit:

    I think for your specific example you would need to use a combination of onChange, onmousedown and onkeydown.

    Your input html would look like:

    <input id="in" type="number" step="0.00000001" onmousedown="downValue(this.value)" onkeydown="resetValue()" onChange="changeValue(this.value)" />
    

    And you would need to use some javascript to store and check the change of the values like so:

    var storedValue = "";
    
    function downValue(e) {
        storedValue = e;
    }
    
    function changeValue(e) {
      if (storedValue !== "" && storedValue !== e) {
         console.log("Do Something");
      }
    }
    
    function resetValue() {
      storedValue = "";
    }
    
    Login or Signup to reply.
  2. Do you mean like this?

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

    const inputElement = document.querySelector('input[name="my-number"]');
    const result = document.querySelector(".result");
    
    inputElement.addEventListener("change", (event) => {
      result.textContent = `Your number ${event.target.value}`;
    });
    <input type="number" step="0.01" name="my-number">
    
    <div class="result"></div>
    Login or Signup to reply.
  3. As a complement for my comments:

    const input = document.querySelector("[type=number]");
    let temp = input.value;
          
    input.addEventListener("input", _ => {
        if (input.value > temp){
            console.log("The new value is greater than the old one");   
        }
        else if (input.value < temp){
            console.log("The new value is lesser than the old one");
        }
        else{
            console.log("The value stays the same");
        }
        
        temp = input.value;
    }, false);
    <input type="number" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search