【问题标题】:Show an error when sum value is over 100总和值超过 100 时显示错误
【发布时间】:2017-06-14 15:45:42
【问题描述】:

我正在尝试对可变数量的输入字段求和 100。我正在使用这个 Javascript:

$('.price').keyup(function () {
    var sum = 0;

    $('.price').each(function() {
        sum += Number($(this).val());
    });

    $('#totalPrice').val(sum);
});

而且它有效!但现在我需要做两件事;如果用户输入的值不是数字,或者总值超过 100,则显示隐藏的 div。

我真的是新的 Javascript,我编写了这段代码,但显示错误现在对我来说是主要词。

谢谢你们!

【问题讨论】:

    标签: javascript jquery sum


    【解决方案1】:

    你可能想要这样的东西:

    $('.price').keyup(function() {
      var sum = 0;
      $('.price').each(function() {
        var inputVal = +$(this).val(); //each field's value converted to number using "+"
        if (!isNaN(inputVal)) {
          sum += inputVal;
          $('.not-num-err').hide();
        } else {
          $('.not-num-err').show();
          return false; //stop iteration
        }
      });
      if (sum > 100) {
        $('.over-hundred-err').show();
      } else {
        $('.over-hundred-err').hide();
      }
      $('#totalPrice').val(sum);
    });
    .hidden {
      display: none
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" class="price">
    <input type="text" class="price">
    <input type="text" class="price">
    <div class="not-num-err hidden">You entered wrong number</div>
    <div class="over-hundred-err hidden">Total is over 100!</div>
    <p>
      <label for="totalPrice">Total Price</label>
      <input type="text" id="totalPrice">

    查看link 了解有关一元加号 (+) 运算符的更多信息。

    【讨论】:

      【解决方案2】:

      你可以在里面使用this关键字:

      $('.price').keyup(function() {
        if (isNaN(this.value) || (!isNaN(this.value) && this.value > 100)) {
          // Do something.
          alert("No!");
          // Do not allow the function to proceed.
          return false;
        }
        var sum = 0;
      
        $('.price').each(function() {
          sum += Number($(this).val());
        });
      
        $('#totalPrice').val(sum);
      });
      

      【讨论】:

      • 这更好地与 isNaN 结合在某处,因为它不会根据要求消除非数字值。
      【解决方案3】:

      工作小提琴:https://jsfiddle.net/ash06229/ydbjsx1z/

      试试这个:

      $('.price').keyup(function () {
          var sum = 0;
          $('.price').each(function() {
              if(sum <= 100)
              {
                    $('.error').html("");
              sum += Number($(this).val());
            }
            else {
              $('.error').html("Sum is greater than 100").css("color","red");
            }
          });
              $('#totalPrice').val(sum);
      });
      

      【讨论】:

      • 当用户输入不是数字的东西时怎么样?
      • 我输入了 type="number";因此无法输入任何文本。 jsfiddle.net/ash06229/ydbjsx1z
      • OP 说:> "如果用户输入的值不是数字,或者如果总值超过100,显示隐藏div.",也就是说,他的输入是type="text"
      猜你喜欢
      • 2015-11-06
      • 2015-02-22
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      相关资源
      最近更新 更多