0

I have a textbox which keeps track of old data and verifies with new data on keyup event. But this works well for single field.

$(function() {
    var content = $('#myContent').val();

    $('#myContent').keyup(function() { 
        if ($('#myContent').val() != content) {
            alert('Content has been changed');
        }
    });
});
<input type="text" id="myContent" class="field1">

Say if there are multiple fields with the same class then how can we track the old data and verify with new data?

0

2 Answers 2

2

There are many ways but below is one of the way to retain original value in data attribute and compare it with entered value on keyup event.

See below code

$(function(){
  //store original value in data attribute
  $('input.field1').each(function(){
     $(this).data('original', $(this).val());
  });
  
  //set keyup event handler
  $('input.field1').on('keyup', function(){
     var changedValue = $(this).val();
     if(changedValue != $(this).data('original')) {
       console.log('Value changed');
     } else {
       console.log('Value same');
     }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id="myContent1" class="field1" value="value1"><br>
<input type="text" id="myContent2" class="field1" value="value1"><br>
<input type="text" id="myContent3" class="field1" value="value1"><br>
<input type="text" id="myContent4" class="field1" value="value1"><br>

Sign up to request clarification or add additional context in comments.

Comments

0

Here's something similar to the first answer but saves the original value when the user focuses on the input. There's also a working fiddle.

$('.field1').on('focus', function() {
  $(this).data('value', $(this).val());
}).on('keyup', function() {
  if ($(this).data('value') != $(this).val()) {
    console.log('Content has changed');
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.