AndraD
AndraD

Reputation: 2850

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.

Upvotes: 3

Views: 6689

Answers (4)

This is how I did it:

jQuery( "#spinner" ).spinner({ min: 0 });

jQuery( "#spinner").keyup(function() {
            if(  isNaN (jQuery(this).val() )){ //Only numbers !
                jQuery(this).prop("value", "0") ; //Back to 0, as it is the minimum
            }
      });

Done.

Upvotes: 0

AJ Quick
AJ Quick

Reputation: 171

I think this is the proper way to do this, not the accepted way since this is much simpler.

$('YOURID/CLASS').spinner({
    min: 1,
    max: 100,
    change: function (event, ui ) {
        $(this).spinner('value', parseInt($(this).spinner('value'),10) || 1);
    }
});

Any input that is not a number will be replaced by the number 1. You could also replace the || 1 with an alert box to alert the user that the number they input into the box is not valid.

You should also use a javascript validator to check the number upon form submission, and another one server side when reading the input in.

Upvotes: 0

Hugo
Hugo

Reputation: 6444

You could set it to readOnly:

document.getElementById('mySpinner').readOnly = true;

Upvotes: 0

user234932
user234932

Reputation:

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.

Upvotes: 8

Related Questions