【问题标题】:jQuery Greater than and Smaller than checkjQuery大于和小于检查
【发布时间】:2020-01-25 19:05:43
【问题描述】:

这是我的表格:

<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>

我的 jQuery 工作:

$('.fms-quote-form').submit(function() {

if ( $('#fms-zip').val() >= 90000 AND <=96162 ) {
  return true;
} else {
    window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
    return false;
  }
});

我如何 (i) 检查 #fms-zip 的值是否大于 90000 且小于 96162 以提交表单,以及 (ii) 如果输入任何其他值,则将用户重定向到另一个网站?

期待您的意见:)

【问题讨论】:

  • 你必须使用 && 而不是 AND
  • 始终检查错误控制台!

标签: javascript jquery if-statement logical-operators


【解决方案1】:

始终检查错误控制台 - 您假设语法错误。 AND 将抛出错误 - 你需要 &amp;&amp;

此外,您不能只指定较高的数字并假设 JavaScript 会知道将其与您比较较低值的同一主题值进行比较 - 您必须重复主题。

let val = parseInt($('#fms-zip').val());
if (val >= 90000 && val <= 96162 ) { //<-- note 2 references to @val

正如@Alessio Cantarella 指出的那样,您还需要将值转换为数字 - 读取字段的值会返回一个字符串。

【讨论】:

    【解决方案2】:

    要检查 ZIP 是否大于 90000 且小于 96162,您需要使用:

    $(function() {
      $('.fms-quote-form').submit(function() {
        let zip = parseInt($('#fms-zip').val());
        let isZipValid = zip >= 90000 && zip <= 96162;
        if (isZipValid) {
          return true;
        } else {
          window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
          return false;
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form class="fms-quote-form" action="https://web.com/quotes" method="get">
      <input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
      <input type="submit" value="Get My Rates">
    </form>

    【讨论】:

      【解决方案3】:

      你可以这样尝试-

      $(function() {
        $('.fms-quote-form').submit(function() {
          var valueZip= parseInt($('#fms-zip').val());
      
          if (valueZip >= 90000 && valueZip <= 96162) {
            return true;
          } else {
            window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
            return false;
          }
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多