show hide div on click
HTML / JavaScript / jQuery

Allow Only Numbers in Text Box using jQuery

Allow Only Numbers in Text Box

Hi, I am writing this tutorial to help you to allow only numbers in the text box using jQuery. So let’s create an input box first and then create prepare an error message like the given example.

<input type="text" name="phone" id="phone" class="form-control" autocomplete="off" />
<span class="text-danger" id="error" style="display: none;">Only numbers are allowed</span>

Now we will write some jQuery to get what we want. Make sure to include jQuery before adding the below-given code.

$("input[name='phone']").keypress(function(e){
  $("#error").text('');
  if(e.which != 8 &amp;&amp; e.which != 0 &amp;&amp; (e.which < 48 || e.which > 57)){
    $("#error").text('Only numbers are allowed');
    return false;
  }
});

In the above code, we are using the which property of JavaScript to detect which key has been clicked. It will help us to make the input box which will allow only numbers in text box. After that, we have given some conditions to prevent the alphabet key press. If the user presses any alphabetical key the error message will be showing.

Try the above solution. It will help you but if you still need any help you can ask in the comments below.

Thanks

Author

I am a Full Stack Web Developer. I have more than 8 years of experience in the web design and development industry.

Leave a Reply

Your email address will not be published. Required fields are marked *