David
David

Reputation: 41

Update other values based on position and value of jQuery UI slider

I'm building a basic mortgage calculator using jQuery and need to display some values which dynamically change based on the current value of the slider.

The values are basic maths such as displaying a percentage of the current slider value or displaying double the value of the current slider value.

Here's where I am with the jQuery and I imagine I need to somehow perform some maths on the last three lines to get the correct values and display these in the HTML elements.

HTML:

<div id="slider"></div>
<p>Your slider has a value of <span id="slider-value"></span></p>
<p>Double the slider value is <span id="slider-double"></span></p>
<p>10% of the slider value is <span id="slider-percent"></span></p>

jQuery:

$("#slider").slider({
value: 100,
min: 0,
max: 1000,
step: 1,
 slide: function(event, ui) {
$("#slider-value").html(ui.value);
}
});

$("#slider-value").html($('#slider').slider('value'));
$("#slider-double").html($('#slider').slider('value'));
$("#slider-percent").html($('#slider').slider('value'));

I'm working on it here where the html is also displayed: https://jsfiddle.net/chlorinekid/mwydgj82/6/

Any thoughts? Many thanks in advance.

Upvotes: 1

Views: 765

Answers (2)

Rikijs
Rikijs

Reputation: 768

If you want to update slider affected values when slider value is chosen (when slider is released)

In order to retain previously set value in the slider one has to use change event of the slider.

$('#slider').slider({
    change: function(event, ui) {
      updateSliderDouble(ui.value);
      updateSliderPercent(ui.value);
    }
});

Please refer to my fiddle example http://jsfiddle.net/mwydgj82/29/

If you want to update slider affected values while slider is moving

in this case one has to use slide event of the slider.

$("#slider").slider({
    value: 100,
    min: 0,
    max: 1000,
    step: 1,
    slide: function(event, ui) {
        $("#slider-value").html(ui.value);
        updateSliderDouble(ui.value);
        updateSliderPercent(ui.value);
    }
});

Please refer to my fiddle example http://jsfiddle.net/9ousgtyd/1/

Upvotes: 1

mohammad
mohammad

Reputation: 1028

I think you are looking for something like this:

    $("#slider").slider({
        value: 100,
        min: 0,
        max: 1000,
        step: 1,
        slide: function(event, ui) {
            $("#slider-value").html(ui.value);
            $("#slider-double").html(ui.value*2 + " double");
            $("#slider-percent").html(ui.value/10 + "%");
        }
    });

    $("#slider-value").html($('#slider').slider('value'));
    $("#slider-double").html($('#slider').slider('value')*2 + " double");
    $("#slider-percent").html($('#slider').slider('value')/10 + "%"); 

Upvotes: 0

Related Questions