Allow only numbers or digits in Razor textbox in asp.net mvc 3 using jquery


hi guys… here i would like to explain about how to allow only numbers in textbox in razor, for this i am using jquery, so in order to do this first we need to download jQuery library file and add it to your web form then write the following code in ur .cshtml form

in the following code we need to give textbox id in keydown function which is shown in blue color

Code in Razor View:

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<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>

@Html.TextBox("Textbox1")

Advertisements

3 thoughts on “Allow only numbers or digits in Razor textbox in asp.net mvc 3 using jquery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s