1

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>
5
  • 1
    And the problem you're having with it is...? Other than the missing ) if your if/else Commented Mar 26, 2018 at 16:00
  • 2
    You code works fine if you include the missing ) on your if statement Commented Mar 26, 2018 at 16:02
  • Or use a placeholder attribute for default text. Commented Mar 26, 2018 at 16:03
  • the logic is fine, where to keep the original value is another matter.. I would use a data-* attribute to avoid having variables for each input you're interested to do this with.. but if you fix your typo the basics are ok :) Commented Mar 26, 2018 at 16:06
  • IMO this shouldn't be downvoted or closed.. even if it's pretty simple, it's someone trying to learn and we shouldn't "punish" that.. and it started some interesting questions on the side in the comments and answer.. so +1 from me.. Commented Mar 26, 2018 at 16:12

1 Answer 1

3

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 
   }
});
Sign up to request clarification or add additional context in comments.

4 Comments

But the code works fine if they fix the missing ) typo
@j08691 Nope, OP shown just an example, what if there's another value in the textfield initially, what do you speak of?
you could argue that it works even better if it's not considered changed if it's edited back to the original value.. :)
@nicael yup. I'm going strictly by what the OP posted -- not every potential possibility

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.