jqueryjquery-uilimitjquery-slider

Limit jQueryUI Slider to go below an amount


I need to "freeze" the slider if user selects something from the checkboxes. My code is as follows:

$('#slider').slider({
            range: 'min',
            value: 20,
            min: 0,
            max: 500,
            slide: function(event, ui) {
                $('input#amount').val('$' + ui.value);
            }
        });
$('div.checkboxes').children('p').children('input').each(function() {
    $(this).change(function() {
        var amount = $(this).attr('data-amount'),
            curr = $('input#amount').val().replace('$',''),
            newPrice = parseFloat(curr)+parseFloat(amount),
            oldPrice = parseFloat(curr)-parseFloat(amount);

        if($(this).is(':checked')) {
            $('#slider').slider({
                'value': newPrice
            });
            $('input#amount').val('$' + newPrice);
        } else {
            $('#slider').slider({
                'value': oldPrice
            });
            $('input#amount').val('$' + oldPrice);
        }
    })
})

As you can see, it slides to some range when one or more checkboxes are checked. But my problem is - when user clicks on each checkbox and then manually slide the price down. What can I do to prevent this?


Solution

  • The only way I know is to check the value in the slide function and if it's not respect you limit return false from the function itself.

    In my example I set a globally scoped variable prizeLimit from a button (but I can be set everywhere) and in the slider slide event I check the variable.

    Code:

    var prizeLimit = 0;
    
    $(document).ready(function () {
    
        $('#amount').val('$20');
    
        $('#slider').slider({
            range: 'min',
            value: 20,
            min: 0,
            max: 500,
            slide: function (event, ui) {
                if (ui.value < prizeLimit) return false;
    
                $('#amount').val('$' + ui.value);
            }
        });
    
        $('#setPrizeFree').click(function () {
            prizeLimit = 0
        });
    
        $('#setPrizeMin').click(function () {
            prizeLimit = 158
            $('#slider').slider({
                'value': 158
            });
            $('input#amount').val('$158');
        });
    
    });
    

    Demo : http://jsfiddle.net/IrvinDominin/3bCzb/