I have a web application and i want a textbox in which user cannot type any thing expcet numeric(0-9) data.
How can we achieve this using jquery?
thanks
I have a simple and quick solution for it, use this jquery code
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
it should work, test it and let me know, thanks
Here is another solution to allow only numbers ins textbox using jquery
$(document).ready(function () {
//called when key is down
$("#number").bind("keydown", function (event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
} else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
});
this code will allow only numbers, and it will not allow cut-copy-paste in textbox
Allow only numbers using Inline Javascript code as below
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
OR
With jQuery
$('input[name="yourInputName"]').keyup(function(e)
{
if (/\D/g.test(this.value))
{
// remove non-digits from input value.
this.value = this.value.replace(/\D/g, '');
}
});
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly