Input that only accepts numeric values

Posted by: Alex on April 13, 2014

Javascript is a key way to help users validate forms and inputs, ensuring they can only enter data that is valid.

A common requirement is an element/input that should only accept numerical values.

The following Javascript does just that, only allowing numbers to be entered, if you type any other value, it simply doesn’t get accepted/show.

  $('.number_only').keypress(function(event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {

Try typing a few things in the below input, you will notice only numbers get accepted: