Richard
Richard

Reputation: 4415

jQuery UI Spinner - Able to exceed `max` by keyboard

We are having issues with the jQuery UI spinner. When we set a max on the spinner, is is not possible to exceed this max when using the spinner button. However using the keyboard we can go to any number.

http://jsfiddle.net/Uygt2/

We need to allow users to use the keyboard as well though. Is there a standard solution for this in jQuery UI?

As you can see in this (http://jsfiddle.net/Uygt2/4/) updated fiddle from Rab Nawaz, the blur always gets called, which is causing our logic to run twice.

Upvotes: 7

Views: 4761

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

EDIT: to handle negative numbers. Thanks to Rzassar for pointing it out.

You can use oninput event: { 'keyup paste' for older browsers which don't support it }

Demo jsFiddle

$("input").spinner({
    max: 10,
    min: -10
}).on('input', function () {
    if ($(this).data('onInputPrevented')) return;
    var val = this.value,
        $this = $(this),
        max = $this.spinner('option', 'max'),
        min = $this.spinner('option', 'min');
    // We want only number, no alpha. 
    // We set it to previous default value.         
    if (!val.match(/^[+-]?[\d]{0,}$/)) val = $(this).data('defaultValue');
    this.value = val > max ? max : val < min ? min : val;
}).on('keydown', function (e) {
    // we set default value for spinner.
    if (!$(this).data('defaultValue')) $(this).data('defaultValue', this.value);
    // To handle backspace
    $(this).data('onInputPrevented', e.which === 8 ? true : false);
});

Upvotes: 13

David Gard
David Gard

Reputation: 12047

I know I've missed the boat, but for a self-containded spinner that acts in the way you require, you could use the spinchange event -

$('input').spinner({
    min: 0,
    max: 3,
    page: 10,
    change: function(event, ui){

        var value = this.value
            min = this.min,
            max = this.max;

        if (!value.match(/^\d+$/)){ // Value is non-numerical

            /** Set the value to the previous value */
            value = 0 

        } else { // Value is numerical

            /** Check that value falls within min and max range */
            if(value > max){
                value = max;
            } else if(value < min){
                value = min;
            }

        }

        /** Send the correct value to the spinner (if it needs changing) */
        if(value !== this.value){
            $(this).spinner("value", value);
        }

    }
});

Upvotes: 0

Richard
Richard

Reputation: 4415

Just for reference, I came up with this solution myself:

    $("input").spinner({
        stop: function (event, ui) {
            $(this).change();
        }
    }).change(function () {

        // min/max calculations
        callFunction();

    });

Which seems to work fine, but roasted's answer looks better.

Upvotes: 0

Related Questions