jQuery检查输入值是否在更改时增加/减少

时间:2015-07-23 21:45:09

标签: javascript jquery input onchange detection

我有一个输入类型编号

<input type="number" value="5" id="nmovimentos"/>

我希望在值增加或减少时执行特定操作(警告更简单的示例)。

我有以下jQuery代码:

$(document).ready(function(){
    var oldValue = $("#nmovimentos").val();
  $("#nmovimentos").change(function(){
    var newValue = $(this).val();
    if (newValue > oldValue)
        alert("increase!");
     else
         alert("decrease!");
  });
});

但是它不起作用,因为它无法检测到oldValue var ..所以有关如何做到的任何线索?非常感谢你!

Jsfiddle

3 个答案:

答案 0 :(得分:4)

您可以使用每个HTMLInputElement必须存储以前值的某些属性,例如defaultValue。在这种情况下,您可以保存几行代码,并使代码更简洁,更简洁:

$("#nmovimentos").change(function () {
    var direction = this.defaultValue < this.value
    this.defaultValue = this.value;
    if (direction) alert("increase!");
    else alert("decrease!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="5" id="nmovimentos" />

答案 1 :(得分:3)

更新处理程序中的std::ofstream outputfile;

&#13;
&#13;
oldValue
&#13;
$(document).ready(function() {
 var oldValue = $("#nmovimentos").val();
  $("#nmovimentos").change(function() {
    var newValue = $(this).val();
    if (newValue > oldValue)
      console.log("increase!");
    else
      console.log("decrease!");

    oldValue = newValue;
  });
});
&#13;
&#13;
&#13;

,使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type="number" value="5" id="nmovimentos" />属性跟踪

&#13;
&#13;
data-*
&#13;
$(document).ready(function() {
  $("#nmovimentos").attr('data-prev-val', $("#nmovimentos").val());
  $("#nmovimentos").change(function() {
    var newValue = $(this).val();
    if (newValue > $(this).attr('data-prev-val'))
      console.log("increase!");
    else
      console.log("decrease!");

    $("#nmovimentos").attr('data-prev-val', newValue);
  });
});
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您必须先在某处保存旧值。 jQuery.data()对此非常方便。

$(document).ready(function(){
  var nmovimentos = $("#nmovimentos");
  var oldValue = nmovimentos.val();
  nmovimentos.data("oldValue", oldValue);
  
  $("#nmovimentos").change(function(){
    var oldValue = $(this).data("oldValue");
    var newValue = $(this).val();
    if (newValue > oldValue)
        alert("increase!");
     else
         alert("decrease!");
    $(this).data("oldValue", newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" value="5" id="nmovimentos"/>

相关问题