ali
ali

Reputation: 11

How to accept only number in the input field using js

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>

Upvotes: 1

Views: 221

Answers (1)

ShadowLp174
ShadowLp174

Reputation: 532

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)

Upvotes: 1

Related Questions