1

How to make the input box accept only numbers in the input field using js event listener.

  <form action="#">
     <label for="value">Value:</label>
     <input type="text" name="value" id="value" />
     <button type="submit">Convert</button>
     <button type="reset">Clear</button>
  </form>
 

<script>
    form.addEventListener(`submit`, function(event){
        event.preventDefault();
    });    
</script>
3
  • 5
    You can change type="text" to type="number" Commented Dec 17, 2021 at 21:15
  • You can use typeof parseInt(input) == „number“. This will try to parse the input to a number and then check if parseint returns a number or something else using typeof Commented Dec 17, 2021 at 21:18
  • 2
    And remember that anyone can open developer tools to get around any client side validation you attempt to make. Always double-check that your inputs are valid on your server-side code before using it. Commented Dec 17, 2021 at 21:18

1 Answer 1

1

You can parse the input to a number and then check if it is a number or something else like NaN.

if(typeof parseInt(input) ==="number"){
  console.log("number!");
}

Please note that anyone can bypass this using the dev tools so don't forget to implemnt server-side validation.(Thx for the tip @samathingamajig)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.