4

How to detect was input value changed or not on blur event?

For example every input field have default value (can be empty), after current input loses it's focus we should determine, have the value been changed.

How to do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Yekver
  • 4,985
  • 7
  • 32
  • 49

5 Answers5

6

Subscribe for .change() instead of .blur(). This way you will know that the value has changed.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    This does not answer the question. – Josiah Ruddell Nov 07 '11 at 22:31
  • @JosiahRuddell, well I don't know whether it answers the question or not. We don't have enough context to draw such conclusions. For me answering a question on SO is not just blindly answering a question the OP asked. It's also offering better alternatives that the OP might not have considered. But I agree that here we don't have enough context so I just posted what came to mind hoping that the OP will make his question more clear. – Darin Dimitrov Nov 07 '11 at 22:33
  • Thanks for the clarification. I was mixing up the change event with a key event. This seems to be the best answer. – Josiah Ruddell Nov 07 '11 at 23:30
6

You could switch to the .change() event instead of .blur(), but I believe that to be fundamentally flawed in a variety of ways. I suggest using Jonathan Azoff's Changed jQuery plugin (http://www.azoffdesign.com/changed). That may be overkill in this case, so...

There are many ways to do this, one of which is to store the old value as a data attribute for an input, then compare the value of the input to the old value on blur. If the two values are different, then it changed.

Example:

    <input type="text" name="firstname" data-old="Jack">

You can store this value using your back-end type thing, or even do it on page load. Then on blur, you can have an event that works something like this:

    $('input').blur(function() {
        if ($(this).data('old') != $(this).val())
            // It changed! Do something!
    }

If the old value was "Jack", and then you changed the name to "Bob" and triggered the blur event, it would see that "Jack" is not equal to "Bob", and perform your action.

Hope that helps. Good luck.

Jemaclus
  • 2,356
  • 1
  • 15
  • 13
4

Directly from the jQuery documentation

$("input[type='text']").change( function() {
  // check input ($(this).val()) for validity here
});
comu
  • 921
  • 1
  • 11
  • 29
3

compare the value and the defaultValue

<input onblur="if(this.value!=this.defaultValue){alert('changed');}">
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
1

You can save value of input on focus, and check it with value from input on blur.

pomaxa
  • 1,740
  • 16
  • 26