Last active
October 6, 2017 00:00
-
-
Save AmrMekkawy/afff4c9f3318d9d4d98246964edb2bd1 to your computer and use it in GitHub Desktop.
Make a text field accepts only digits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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