lewis4u lewis4u - 7 months ago 32
Javascript Question

jQuery prevent writing letters and change comma to dot

I have tried to modify this code but it just wont work...probably some small mistake but i can't debug it :(

// replace , with . and block writing letters
$(document).on("keydown", ".amount", function () {
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
};


This is original code and it doesn't work on dynamic content
that is why i want to modify it!

Answer

How about just calling your ForceNumericOnly method when the user clicks into an input with .amount?

$(document).on('focus', '.amount', function(){
    $(this).ForceNumericOnly();
});

https://jsfiddle.net/daveSalomon/r5n8xuhx/5/

You could (should) optimise it so it doesn't add the keydown handler again if it's already run the ForceNumericOnly code... something like:

$.fn.ForceNumericOnly = function() {
    return this.each(function() {
        if($(this).data('forceNumberOnly'){ return; }
        $(this).data('forceNumberOnly',true);
        ...
    });
};

https://jsfiddle.net/daveSalomon/r5n8xuhx/6/

Comments