compare two input values using Jquery

我是研究僧i 提交于 2021-02-11 11:52:13

问题


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; 
  }
});

回答1:


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()) {



回答2:


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; 
  }
});



回答3:


$("#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



来源:https://stackoverflow.com/questions/37988241/compare-two-input-values-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!