Skip to content

Instantly share code, notes, and snippets.

@AmrMekkawy
Last active October 6, 2017 00:00
Show Gist options
  • Save AmrMekkawy/afff4c9f3318d9d4d98246964edb2bd1 to your computer and use it in GitHub Desktop.
Save AmrMekkawy/afff4c9f3318d9d4d98246964edb2bd1 to your computer and use it in GitHub Desktop.
Make a text field accepts only digits
$(function() {
// Remove any character or symbole and keep only
// numbers in the "Reference Number" input field
$("input[type=text]").on("keyup keydown", function() {
var refNumber = keepOnlyNumbers($(this).val());
$(this).val(refNumber);
});
});
// Remove any character or symbol withen
// the provided value and keep only numbers
function keepOnlyNumbers(value) {
if (value.length === 0) {
return "";
}
var items = value.split("");
var filteredItems = [];
items.forEach(function(val, index){
// If val is a number
if (! isNaN(parseInt(val.trim()))) {
filteredItems.push(val);
}
});
return filteredItems.join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment