Marwan Fikrat Marwan Fikrat - 24 days ago 17
Javascript Question

Accessing slider values

I am more versed in PHP but I have to code a loan calculator using javascript and jquery ui.

I have 3 sliders, here the code of one of them:

$('#amountSlider').slider({
range: "min",
value: 37,
min: 1000,
max: 20000,
slide: function( event, ui ){
$("#amount").val( "$" + ui.value );
}
});
$("#amount").val("$" + $("#amountSlider").slider("value"));


HTML where the values are output:

<input type="text" name="amount" id="amount"><br>
<input type="text" name="rate" id="rate"><br>
<input type="text" name="term" id="term"><br>
<input type="text" name="calcTotal" id="calcTotal"/>


The sliders work fine and show the value in the text box but I can't seem to access the values outside the sliders to add them all into a
total calculation
text box.

Example:

Slider 1 value : 50
Slider 2 value: 3
Slider 3 value: 5.5


I'd like to be able to say :
calcTotal = slider1.val + slider2.val + slider3.val
and that the value is always updating as i drag the slider.

A live example I found is the homepage calculator at : http://blinkfinance.com.au/

Appreciate your help, thank you.

Answer

Call a function, which accesses the other values and sum them there up. Of course you could then split this all up in a service, cache the elements etc. but you get the idea.

$( function() {
    var output = $('#output');
    
    $( "#slider1" ).slider({
        slide: function( event, ui ) {
            
            output.text( getAllValues() );
        }
    });
    
    $( "#slider2" ).slider({
        slide: function( event, ui ) {
            output.text( getAllValues()  );
        }
    });
    
    $( "#slider3" ).slider({
        slide: function( event, ui ) {
            output.text( getAllValues() );
        }
    });
    
    
    function getAllValues() {
        return getValue("1") + getValue("2") + getValue("3");
    }
    
    function getValue(id) {
        return $("#slider" + id).slider("value");
    }
});
@import url(http://fonts.googleapis.com/css?family=Lato:400,700);

body {
  background-color: #f0f0f0;
  color: #333;
  font-family: Lato, Helvetica, Arial, sans-serif;
  margin: 25px;
}
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  
  <div id="slider1"></div>
  <br>
  <div id="slider2"></div>
  <br>
  <div id="slider3"></div>

<br><br>

<div id="output">Drag..</div>

Comments