On () to keep track of input changes

$("#myTextBox").on("change paste keyup", function() {
   alert($(this).val()); 
});

How to compare the new value inserted by the user and the current value that was already at the input?

+4
source share
4 answers

Oddly enough, the input attribute is valuenot actually updated when its value changes. Therefore, you can simply compare .val()with attr("value")and update attr("value")after making changes:

eg:

$("#myTextBox").on("change paste keyup", function() {
   alert($(this).attr("value")+" vs "+$(this).val());
   $(this).attr("value",$(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextBox" value="abc" />
Run codeHide result
+1
source

Here you can use closure:

  $("#myTextBox").on("change paste keyup", (function() {
    var previousValue = $("#myTextBox").val();
    return function() {
        var newValue = $(this).val();
        alert('Was ' + previousValue + " and now it " + newValue);
        previousValue = newValue;
    };
})());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextBox" value="abc" />
Run codeHide result

: previousValue, , , . .

+3

, .

$("#myTextBox").on("change paste keyup", function() {
  // Get previous and current value
  var prevValue = $(this).data('value'),
    currValue = $(this).val();
  console.log(prevValue + ' === ' + currValue);

  // Update the prevValue
  $(this).data('value', currValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="myTextBox" type="text" />
Hide result
+2

, JavaScript, :

  • .

- , - : var previousValue = $(this).val();

...

$("#myTextBox").on("change paste keyup", function () {
    var preValue = $(this).val();
    return function () {
        var newValue = $(this).val();
        consol.log('preValue: ' + preValue + 'newValue: ' + newValue);
        preValue = newValue;
    };
});

The return occurs after, so it works, I like the callback, it mainly happens after and so you can save both variables ...

0
source

Source: https://habr.com/ru/post/1624252/


All Articles