javascriptjqueryjquery-ui-spinner

jQuery Spinner: Non-numerical values


I am using the jQuery Spinner, with min (0) and max (500) values set up. What can I do to prevent the user from directly entering non-numerical values (or values outside the 0-500 range) in the input box? The min and max values work when the user uses the spinner buttons, but not when something is typed into the input form.


Solution

  • You can force numeric input using a technique like this:

    var MIN = 0;
    var MAX = 500;
    
    $('#foo').on('keyup', function(e) {
      var v = parseInt($(this).val());
      if (isNaN(v)) {
         return $(this).val(MIN);
      }
      if ($(this).val() < MIN) {
         $(this).val(MIN);
      } else if ($(this).val() > MAX) {
         $(this).val(MAX); 
      } else {
         $(this).val(v);
      }
    });
    

    (See example: http://jsfiddle.net/foxbunny/ustFf/)

    But I do not recommend it. It's not the expected text box behavior, and it tends to confuse at least some of the users. So it's better to just display a warning if the value is not in the expected range.