seb68
seb68

Reputation: 269

How to only accept positive integer in Jquery spinner?

'<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

Answers (6)

Synsane Shots
Synsane Shots

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

Jay Lepore
Jay Lepore

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

Mike Ellis
Mike Ellis

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

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

itsazzad
itsazzad

Reputation: 7277

Use

{decimals:0}

or

{min:0}

or both together in the options

Upvotes: 3

Karthi Keyan
Karthi Keyan

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

Related Questions