Home > front end >  Do something when one input range slider value is less than the other (using jQuery)
Do something when one input range slider value is less than the other (using jQuery)

Time:10-29

I am trying to set the background color of two form input range sliders using jQuery. Users are selecting a minimum and maximum distance, so I would like to alert the user when the minimum distance is larger than the maximum distance. I've tried this using jQuery but the script below does not do the trick for me.

These are my two input range sliders:

<input id="mindistance" class="rangeslider" type="range" name="mindistance" min="0" max="100" value="0" step="5">
<input id="maxdistance" class="rangeslider" type="range" name="maxdistance" min="0" max="100" value="100" step="5">

This is my jQuery at the moment:

$('#maxdistance').blur(function(){
  if ( $(this).val().length <= $('$mindistance').val().length ) {
    $(this).css({ 'background-color': 'rgb(255,175,175)' });
    $('#mindistance').css({ 'background-color': 'rgb(255,175,175)' });
  } else {
    $(this).css({ 'background-color': '' });
    $('#mindistance').css({ 'background-color': '' });
  }
});

I've tried .focusout() instead of .blur() as well, so I suspect the <= operator not working here but I'm not sure. Does anybody know how to do this?

EDIT: both .val() and .val().length don't do the trick.

EDIT: also tried $(document).on('input', '#mindistance', function() { /* check values */ });

CodePudding user response:

First of all, you have an error trying to reference maxdistnce. '$maxdistance' should be '#maxdistance'

i changed a few other things

  • Placed your sliders in divs and changed the bgcolor of these divs instead of the sliders themselves
  • reset the bg colors each time the event occurs
  • used the on change event instead of blur (not necessary)
  • removed .val().length and used .val() alone
<div class="mindistance">
<label>min</label>
<input id="mindistance" class="rangeslider" type="range" name="mindistance" min="0" max="100" value="0" step="5">
</div>
<div class="maxdistance">
<label>max</label>
<input id="maxdistance" class="rangeslider" type="range" name="maxdistance" min="0" max="100" value="100" step="5">
</div>


$(document).on('change', '#mindistance',function(e){
    console.log($(this).val(), $('#maxdistance').val());
  
    $('.mindistance').css({ 'background-color': '' });
    $('.maxdistance').css({ 'background-color': '' });

  if ( $(this).val() <= $('#maxdistance').val() ) {
    $('.mindistance').css({ 'background-color': 'rgb(255,175,175)' });
    $('.maxdistance').css({ 'background-color': 'rgb(255,175,175)' });
  } 
});
  • Related