Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 706
Richard Avatar asked May 28 '13 12:05

Richard


1 Answers

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);
});
like image 74
A. Wolff Avatar answered Sep 24 '22 17:09

A. Wolff