coder12349
coder12349

Reputation: 491

Better way to check if textbox values are changed using jquery

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?

Upvotes: 0

Views: 38

Answers (2)

VVV
VVV

Reputation: 7603

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');
  }
});

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

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>

Upvotes: 2

Related Questions