Travesty3
Travesty3

Reputation: 14479

Disable holding the up and down buttons on a jQueryUI spinner

I'm using jQuery 1.7.1 and jQueryUI 1.9.1.

I have a spinner, and every time it changes, a text field will be created or removed to match the number on the spinner. Holding the button will cause the number to change very rapidly, causing a ton of fields to be created or removed.

Not a huge problem since it's client-side, but I just don't like it. So I want to disable the rapid spinning when the user holds the spinner buttons.

I came up with a solution using a function for incremental, which looks like this:

var incrementalFunction = function(numOfSpins) {
    if (numOfSpins == 1) {
        return 1;
    }
    return 0;
};

This worked great at first, but caused another issue. Next to each newly created text box, I made a 'remove' button that would remove the element and decrement the spinner. But when I call the stepDown method, for some reason, this calls my incremental function, with an increasing numOfSpins every time it was called. So it would only decrement once.

Anyone have a more straightforward solution to preventing the user from holding the increment/decrement buttons (or the up/down arrows on the keyboard)?

Upvotes: 0

Views: 1253

Answers (2)

Scott González
Scott González

Reputation: 1927

If you upgrade to jQuery UI 1.10, the problem will go away. See https://github.com/jquery/jquery-ui/commit/0d53fbfd0b7651652601b3b8577225ab753aab44 which causes stepUp() and stepdDown() to behave as you'd expect.

Upvotes: 1

Ian
Ian

Reputation: 50903

If you use the stop event, instead of targeting each increment, you can detect when a selection has been made. Then, you can compare that number to how many are currently there, and determine what to do - remove or add more. Try this:

var targetArea = $("#target_area");

targetArea.on("click", ".remover", function () {
    $(this).closest("div").remove();
    $("#input1").spinner("stepDown");
});

$("#input1").spinner({
    stop: function (event, ui) {
        var $this = $(this);
        var num = $this.val();

        var newTargets = targetArea.find("div");
        var difference = num - newTargets.length;
        if (difference < 0) {
            newTargets.slice(difference).remove();
        } else if (difference > 0) {
            for (var i = 0; i < difference; i++) {
                var newTarget = $("<div><input type='text' /><span class='remover' title='Remove'>&times;</span></div>");
                targetArea.append(newTarget);
            }
        }
    }
});

DEMO: http://jsfiddle.net/PJpUC/1/

Upvotes: 1

Related Questions