IntroductionIn this snippet I will show you how to create numeric textbox using JQuery.This snippet is allow to enter numbers,backspace keys only. ImplementationCreate new web application with visual studio and add JQuery Library into page from Google CDN. Html code <%@ Page Language="C#" AutoEventWireup="true" CodeFile="numerictextboxdemo.aspx.cs"
Inherits="numerictextboxdemo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to Create Numeric Textbox using JQuery</title>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>And then add a textbox within page rename to txtsalary and make page html as like below, <form id="form1" runat="server">
<div>
<h2>
The Numeric Textbox Live demo
</h2>
</div>
<div>
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
</div>
</form>Now write javascript to only allow numbers. <script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#txtSalary').keydown(function(event) {
if (((event.keyCode == 8 || event.keyCode == 46) || (event.keyCode >= 47 && event.keyCode < 58)) == false) {
event.preventDefault();
}
});
});
</script>
Note:If you are using Master page, you have to use the class to find the control than using IDs. In above script,using keyDown event to textbox and check keycode each key down. If any keycode with in number range, backspace and period then allow to go down otherwise prevent default event of keydown. The ASCII table for keys here The more about event.preventDefault() here Just press F5 and run application try to enter numbers or characters to textbox. Live DemoNumeric TextBox live demo ConclusionIn this snippet, I have demostrated to create numeric textbox using JQuery. Hopes help and thank you for reading. |