Reputation: 269
'<label id="quantite" for="quantite">Quantite : </label><input id="QteSpinner" value="1"></br>'
[...]
var newSpinner = $( "#QteSpinner" ).spinner({
min: 1
});
How could I restrict the user to only type numbers in a JQuery spinner like this one?
Thanks
Upvotes: 4
Views: 7188
Reputation: 1
Or you can check for the keystroke value, and then use $.isNumeric() to test it, like :
$("#spinner").spinner({
min: 1
}).keypress(function(e){
key = e["originalEvent"]["key"];
if (!$.isNumeric(key)){
e.preventDefault();
}
});
Upvotes: 0
Reputation: 153
A slight improvement on Francisco Corrales Morales's as it does not zero out the field. It only removes the alpha entry
jQuery( "#repeat_x").keyup(function() {
if(isNaN (jQuery(this).val() )){
/* however only slicing off the last character instead of setting to 0 */
jQuery(this).prop("value",jQuery(this).prop("value").slice(0, -1));
}
});
Upvotes: 0
Reputation: 1280
Use a change function to map non-integer inputs to a suitable default value, e.g
var myspinner = $( "#myspinner" ).spinner(
{
min: 1,
change: function (event, ui ) {
var val = myspinner.spinner( "value" );
myspinner.spinner("value", parseInt(val,10) || 1);
/*
var val = $(this).spinner( "value" );
$(this).spinner("value", parseInt(val,10) || 1);
*/
}
});
This won't prevent the user from typing nonsense, but it will constrain the values in the spinner as soon as the spinner loses focus. If you absolutely must block typing of anything but numbers, you might be able to do something with the keypress() function. See jquery to check when a someone starts typing in to a field for more details.
Upvotes: 1
Reputation: 3834
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
Reputation: 4393
Take a look at this fiddle link. I have created one sample which will restrict negative numbers in the spinner.
var value;
var $container=$("#QteSpinner");
var newSpinner = $container.spinner({
min: 1,
}).focus(function () {
value = $container.val();
}).blur(function () {
var value1 = $container.val();
if (value1<0) {
$container.val(value);
}
if(isNaN(value1))
{
$container.val(value);
}
});
I hope this will help you more.
Upvotes: 2