Search

Sunday, July 12, 2015
0 comments

Accept only number by TextBox using Jquery

11:41 PMSunday, July 12, 2015
You can say, how to apply restriction on input using Jquery. Here, meaning of restriction is, TextBox accept only numbers. Everyone know that TextBox control take character,string, numeric and special character as a input. But in some application we need only single feature like, it accept only number. So, the first question raise in my mind, how to do this, what is the logic behind this.
Logic behind this:
  1. First to get the key code like number 8 == backspace, some following keycode available here 
  2.  Now, match the keycode with the input character, if match then input character are not allowed.
Here are simple example of it:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Accept only numbers</title>
<script src="scripts/jquery-1.10.2.js"></script>
<script>
$(function () {
$('#Text1').keydown(function (er) {

if (er.altKey || er.ctrlKey || er.shiftKey) {
er.preventDefault();
}
else {

var key = er.keyCode;
if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {

er.preventDefault();
}

}


});

});

</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
<input id="Text1" type="text" />
    </div>
    </form>
</body>
</html>
Now code generate the following output:

Accept only number by TextBox using Jquery
Here are some related article:
Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top