How to Get HTML Spin Box Arrows to Register as OnKeyUp Input

Viewed 604

I have this small HTML file that when I enter a number in the input field, its onkeyup attribute triggers a button

Link here: https://www.w3schools.com/code/tryit.asp?filename=G8P7G9W1MFF4

<!DOCTYPE html>
<html>

<head>
</head>

<body>

  <input type=number min="1" max="5" value="1" class="example" name=text onKeyUp=myFunction();>

  <button id="myBtn" onclick="javascript:alert('Hello World!')">Try it</button>

  <script>
    function myFunction() {
      var x = document.getElementsByClassName("example");
      if (x[0].value > 0) {
        document.getElementById("myBtn").click();
      }
    }
  </script>

</body>

</html>

The function triggers correctly when I type into the input field, but I want to know why the arrows don't trigger the function also.

3 Answers

Because the spin buttons aren't keys and therefore don't register a keyup event. But, you can register for the input event, which will trigger when the buttons are used.

Also, you're using some 25+ year old syntax, which you really should abandon. Don't set up your events inline with HTML and don't use .getElementsByClassName().

<!DOCTYPE html>
<html>
 <head>
  <title>Fun with Events</title>
 </head>
 <body>

  <input  type=number min="1" max="5" value="1" class="example" name="text"> 
  <button id="myBtn">Try it</button>

  <script>
    // Get your element references just once:
    let input = document.querySelector("input.example");
    let btn = document.getElementById("myBtn");

    // Register event handlers
    input.addEventListener("keyup", myFunction);
    input.addEventListener("input", myFunction);

    function myFunction() {
      if(input.value > 0) {
        document.getElementById("myBtn").click();   
      }
    }

    btn.addEventListener("click", function(){
      alert('Hello World!');
    });
  </script>
 </body>
</html>

You should use oninput instead of onKeyUp:

<!DOCTYPE html>
<html>

<head>
</head>

<body>

  <input type=number min="1" max="5" value="1" class="example" name=text oninput=myFunction();>

  <button id="myBtn" onclick="javascript:alert('Hello World!')">Try it</button>

  <script>
    function myFunction() {
      var x = document.getElementsByClassName("example");
      if (x[0].value > 0) {
        document.getElementById("myBtn").click();
      }
    }
  </script>

</body>

</html>

Hi you could use id instead class, like so:

    const input = document.getElementById("myInput");
    const btn = document.getElementById("myButton");
    
    const myFunction = () => {
      if(input.value > 0) {
        btn.click();   
      }
    }
   
    input.addEventListener("keyup", myFunction);
    input.addEventListener("input", myFunction);   

    btn.addEventListener("click", () => console.log("myButton clicked"));
<input id="myInput" type=number min="1" max="5" value="1" class="example" name="text"> 
<button id="myButton">Try it</button>

Related