问题
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.
回答1:
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.
回答2:
You could set it to readOnly:
document.getElementById('mySpinner').readOnly = true;
回答3:
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.
回答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.
来源:https://stackoverflow.com/questions/14206291/jquery-spinner-non-numerical-values