Showing posts with label MVC enter numbers only. Show all posts
Showing posts with label MVC enter numbers only. Show all posts

How to type only numbers in MVC textbox

1. In the step one you have to download or call CDN of jquery.min.js

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js" type="text/javascript"></script>

2. Add textbox in the view by using html helper 

            @Html.TextBox("Textbox1")
     
3. And then code the script like this

<script type="text/javascript">

             $(document).ready(function () {
            $("#Textbox1").keydown(function (event) {
                   if (event.shiftKey) {
                          event.preventDefault();
                  }
         if (event.keyCode == 46 || event.keyCode == 8) {
                 }
        else {
                     if (event.keyCode < 95) {
                          if (event.keyCode < 48 || event.keyCode > 57) {
                                  event.preventDefault();
                         }
                     }
                    else {
                               if (event.keyCode < 96 || event.keyCode > 105) {
                                event.preventDefault();
                              }
                     }
                 }
           });
     });

 </script>

code is 100% work and fine because I have experimented above codes

thank you
Happy coding...!