Friday, April 18, 2014

Allow only numeric or numbers in textbox using Javascript

Hi friends.In this article i am going to show you how to allow numeric values only in textbox using Javascript.

Let's take a look.

Demo

Number:

Jquery Files

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
        $(function () {
        $('#phone_number').keydown(function (e) {
        if (e.shiftKey || e.ctrlKey || e.altKey) {
        e.preventDefault();
        } else {
        var key = e.keyCode;
        if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
        e.preventDefault();
        }
        }
        });
        });

</script>

HTML Code

<form action="#" method="post">
      <input type="text" name="name" id="phone_number"/>
    </form>


If you like this article please post your comments here.Thanks.!!

1 comment:

  1. You can use a simpler JS method:

    isNaN(123); // Returns false, so it is a number
    isNaN("Hello"); // Returns true, so it is not a number

    Remember to always do server side validation too.

    ReplyDelete