Home > JavaScript > jQuery filter user input

jQuery filter user input

I’ve coded small function that allows filter user input to <input> fields.
It allows to press 0-9 keys (incl. NumPad keys), “,” and “.”, Backspace.
It’s enought to write float value.

$(':input.onlynum').keypress(function(event) {
    if (
        // numbers
        (event.which < 48 || event.which > 57) && 

        // .,
        event.which != 44 && event.which != 46 && 

        // backspace
        event.which != 8                      
    ) {
        event.preventDefault();
        return;
    }
})

HTML:

Try to input non-numeric symbols:
<input class="onlynum">
Categories: JavaScript Tags: ,
  1. No comments yet.
  1. No trackbacks yet.