Search code examples
javascriptjqueryhtmljquery-uijquery-ui-slider

How to check value of multiple range sliders on click of button and then do something based off of value?


I have three Jquery UI sliders. When the user clicks on the next button I need to get the value of each individual slider and check each of them in an if else statement. For example if the first slider is less than 10 it would do one thing, if the first and second slider are less than 10 it would do something else.

You can see a live example of my code on Codepen: http://codepen.io/anon/pen/vLdKJv

Here's my HTML:

<div id="eq">
   <span id="one">88</span>
   <span id="two">77</span>
   <span id="three">55</span>
</div>
<br><br>
<div style="width:100%">
   <button>CLICK ME</button>
<div>

Here's my JS

$(function() {
$( "#eq > span" ).each(function() {
  // read initial values from markup and remove that
  var value = parseInt( $( this ).text(), 10 );
  $( this ).empty().slider({
    value: value,
    range: "min",
    animate: true,
    orientation: "horizontal"
  });
  $('button').on('click',function(){
     if(this.value < 10){
     $('body').css('background','red');
         }
       })
     });
  });

Here's my CSS

#eq > span {
 width:120px;
 float:left; 
 margin:15px;
}
#eq{
 width:100%;
 margin: 0 auto; 
 display:block;
 position: absolute;
 left:5%;
}
button{
  position: absolute;
  left:20%;
  margin-top:2%;
}

So right now I'm not sure how to 1. get the value of each slider on click & 2. check each value after the on click & perform a certain task based off the value of the slider.


Solution

  • Here is something to try:

    jsFiddle Demo

    $('#mybutt').click(function(){
        $('#eq>span').each(function(){
            var ndx = $(this).index() +1; //which slider you are on (zero-based, so add 1)
            var val = $(this).slider( "value" );
    
            if (val < 10) $('body').css({'background':'red'});
        });
    });
    

    Also, you could assign each slider and ID and specifically request its value by ID:

    $('#mybutt').click(function(){
        $('#rpt').html('');
        var s1 = $("#one").slider( "value" );
        var s2 = $("#two").slider( "value" );
        var s3 = $("#three").slider( "value" );
    
        if (s1 < 10) {
            $('body').css({'background':'red'});
        }else if (s2 < 10){
            $('body').css({'background':'green'});
        }else if (s3 < 10){
            $('body').css({'background':'blue'});
        }
    
        $('#rpt').html('s1:['+s1+']   s2:[' +s2+ '   s3:['+s3+']');
    });
    

    New jsFiddle Demo