steve_o
steve_o

Reputation: 1243

jQuery ui spinner - using for time (hours)

Using jQuery 1.9.1 & jQuery-ui 1.10.3. Want to use a spinner for a time (hours) control. In addition to having a finite set of values, I want to have it roll over to 0 once it has gone beyond 23. I have that part working. What I am having problems with is when it starts.

The code I use for the spinner:

$(function() {
    $("#mystarttime").spinner({
        numberFormat: "d2",
        spin: function(event, ui) {
            if (ui.value > 23) {
                $(this).spinner("value", 0);
                return false;
                    }
            else if (ui.value < 0) {
                $(this).spinner("value", 23);
                return false;
                    }
            console.log("start spin - " + ui.value );
            }
        });
});

The input:

<label for="mystarttime">Start Time (hr):</label>
<input type="text" id="mystarttime" name="startTimeVal">

When the page loads, the spinner has nothing in it. If I click the up arrow on the spinner (to increment), the spin event fires & I get a message in the console showing the value (1). However, if I click the down arrow on the spinner, the spin event doesn't fire, but I get a 23 in the input box. It's not until I click the down arrow again that the spin event fires, and the input (and console) both show 22.

If I click the down arrow once, the input box shows 23 (but no event fires). After that, if I click the up arrow once, the input shows 00 (but no event fires).

I must be doing something wrong or looking at the wrong event to detect the roll over & change but haven't found a good example that both rolls over and sees the event. Would appreciate any thoughts or suggestions on how to resolve this.

Upvotes: 1

Views: 4422

Answers (1)

ggzone
ggzone

Reputation: 3711

spin: is not called when you set the value yourself. but change: is called - this should do the trick:

function log(value) {
 console.log(value);
}

$(function() {
    $("#mystarttime").spinner({
        numberFormat: "d2",
        spin: function(event, ui) {
            if (ui.value > 23) {
                $(this).spinner("value", 0);
                return false;
                    }
            else if (ui.value < 0) {
                $(this).spinner("value", 23);
                return false;
                    }
            log(ui.value);
        },
        change: function(event, ui) {
            log($(this).spinner("value"));
        }
        });

});

Upvotes: 1

Related Questions