nicozica
nicozica

Reputation: 423

Check if input field value has changed on button click

I need to check if a value has changed on an input field before submitting a form. This is the code I have so far:

JS

$(document).ready(function(){

    $('#submitButton').click(function() {

        if( $('input[name="inputToBeChecked"]').val() != 'Original input field value' {
            alert("Input field has changed!");
        } else {
            alert("Input field has not changed!");
        }

    });
});

HTML

<form>

  <input type="text" name="inputToBeChecked" id="inputToBeChecked" value="Original input field value">
  <a id="submitButton" type="button" class="btn" href="javascript:void(0);">Submit form</a>

</form>

Upvotes: 1

Views: 2006

Answers (1)

nicael
nicael

Reputation: 19024

Just set a flag once the input has been changed

var flag = 0;
$('input[name="inputToBeChecked"]').change(function(){
   flag = 1;
});
$('#submitButton').click(function() {
   if(flag == 1){
     //yeah!
   }
});

There can be also another case, if it gets changed and then returns to initial state. Then you could just save the initial value instead.

var initialVal;
$(document).ready(function(){
   initialVal = $('input[name="inputToBeChecked"]').val();
});
$('#submitButton').click(function() {
   if($('input[name="inputToBeChecked"]').val() != initialVal){
      // initial value changed
   } else {
      // initial value either unchanged or changed and later reversed to initial state 
   }
});

Upvotes: 3

Related Questions