简体   繁体   中英

noUiSlider set values on page load

I'm using the noUiSlider on a new project of mine.

I have the element within a form that allows the user to select a range of price (min and max). When the form is submitted both values are used in the code to filter items of a range between these two selected prices.

HTML/PHP:

<div id="m-price"></div>

<div class="field field-range">
    <input type="text" min="0" max="5000" step="100" id="price-min" name="price-min" value="<?php echo ($_POST['price-min']) ? $_POST['price-min'] : ''; ?>">
</div>

<div class="field field-range">
    <input type="text" min="0" max="5000" step="100" id="price-max" name="price-max" value="<?php echo ($_POST['price-max']) ? $_POST['price-max'] : ''; ?>">
</div>

JS:

$('#m-price').noUiSlider({
    range: {
        'min': 0,
        'max': 500
    }
    ,step: 100
    ,start: [0,500]
    ,connect: true
    ,serialization: {
        lower: [
            $.Link({
                target: $('#price-min'),
                format: {
                    decimals: 3,
                    mark: ','
                }
            })
        ],
        upper: [
            $.Link({
                target: $('#price-max'),
                format: {
                    decimals: 3,
                    mark: ','
                }
            })
        ]
    }
});

Now this is currently working perfectly, however, I have on the form elements an 'if value exists set that value to the form input(s) value' every time the page reloads (just like a sticky form thing so the user knows what they searched for).

The way the noUiSlider works this is not possible as the element initializes on page load and the values are set using 'start: [0,500]'. I notice there is a 'set' event but how can I use it in this scenario?

This could be solved by setting the value to the slider, instead of to the inputs. Basically, you would get your variable from the POST , and get that to javascript:

<?php 
    $min = $_POST['price-min'];
    $max = $_POST['price-max'];
?>

<script>var startValues = [<?php
    echo isset($min) ? $min : 0;
?>, <?php
    echo isset($max) ? $max : 500;
?>];</script>

Now, you have a value to initiate your slider with:

$('#m-price').noUiSlider({
    ...
    start: startValues 
    ...
});

The Link elements will then write these values to the inputs, or, if they weren't set, default to your initial start values of 0 and 500 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM