Restricted Input box accepting Only number values using Jquery
Posted By : Sanjay Saini | 27-Jun-2015
Hi Friends ,
In this blog, I'm going to explain how to restrict html input box accepting only Numberic values using JQuery.Many times we have need to restrict input box accepting only numberic values. Many ways and plugin available for this.Some time we restricting many keys like backspace, insert ,delete ,Tab and Enter key when Restricting input box .I'm explain you how to restricted input box without restricting these keys.
1 .When You using HTML 5 then Used HTML5 input type number instead of input type text :
Html Code :
<div class="containercontent">
<div class="label">Enter a number:</div>
<input type="number" name="number" id="number" value="" />
<div class="label">Enter a number:</div>
<input type="number" name="number" id="number" value=""/>
</div>
2. Using Jquery Restricting Input box :
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<div class="containercontent">
<div class="label">Enter a number:</div>
<input type="text" name="number" id="number" value="" class="numberinput" />
<div class="label">Enter a number:</div>
<input type="text" name="number" id="number" value="" class="numberinput" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".numberinput").restrictInput();
});
// restrictInput() plug-in implementation
/* Place that code in external js and inclue that js in header of Html After Jquery */
jQuery.fn.restrictInput = function () {
return this.each(function () {
$(this).keydown(function (e) {
var key = e.which || e.keyCode;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45)
return true;
return false;
});
});
}
</script>
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Sanjay Saini
Sanjay has been working on web application development using frameworks like Java, groovy and grails. He loves listening to music , playing games and going out with friends in free time.