简体   繁体   中英

compare two input values using Jquery

I'm trying to compare two values from a dual input range slider. If the bottom value is equal or greater than the top value, I want to return false . This is to prevent overlap between the two thumbs.

I have used .change to listen for changes. I can then console.log & return the value after it's been updated. I have included the last bit of code in the hope for help. You can see an full almost working version here:

https://fiddle.jshell.net/elliottjb7/fj9ot08v/

Thanks

$("input[type='range'][id='text_box_bottom_range']").change(function() {
  var bottom = $("input[type='range'][id='text_box_bottom_range']").val();
  console.log("bottom = " + bottom);
  return bottom;
});

$("input[type='range'][id='text_box_top_range']").change(function() {
  var top = $("input[type='range'][id='text_box_top_range']").val();
  console.log("top = " + top);
  return top;
});     

$("input").blur(function() {
  if ($("input[type='range'][id='text_box_bottom_range']").val() > this.val) {
    console.log("Bottom is higher than Top");
    return false;
  } else { 
  return true; 
  }
});

this line

if ($("input[type='range'][id='text_box_bottom_range']").val() > this.val) {

should be

if ($("input[type='range'][id='text_box_bottom_range']").val() > $("input[type='range'][id='text_box_top_range']").val()) {

Change your blur event on the input element to

$("input").blur(function() {
  if ($('#text_box_bottom_range').val() >= $('#text_box_top_range').val()) {
    console.log("bottom is equal or higher than the top");
    return false;
  } else { 
    return true; 
  }
});
$("#text_box_bottom_range").change(function() {
    return $(this).val();
});

$("#text_box_top_range").change(function() {
    return $(this).val();
});     

$("input").blur(function() {
    if ($("#text_box_bottom_range").val() =>  $("#text_box_top_range").val()) {
        return false;
    } else { 
        return true; 
    }
});

This does the correct check where bottom is:

... equal or greater than the top value

Also, the first 2 functions ( .change() ) are quite redundant for what you are trying to achieve but I've included a better way to write them

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