简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM