Stacker Stacker - 6 months ago 9
jQuery Question

How can I force numbers only on a dynamically created field?

I am trying to restrict a dynamic field to numbers only but if I try:

$(document).on('keydown', '.numberOnly', function() {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode == 65 && (e.ctrlKey ===
true || e.metaKey === true)) || (e.keyCode >=
35 && e.keyCode <= 40)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode >
57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});


But it doesn't work. it does work if I replace the top line with:

$(".numberOnly").keydown(function(e) {


however, that only works for static fields.

Answer

Your method looks just fine, and should work correctly. There was one small typo that you left out the EventObject e from the delegated event binder ( but included it in the direct event binder, which is why it worked ).

Changing the first line to:

$(document).on('keydown', '.numberOnly', function(e) {

should fix your problem