Reputation: 5185
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?
Upvotes: 4
Views: 23070
Reputation: 117334
compare the value and the defaultValue
<input onblur="if(this.value!=this.defaultValue){alert('changed');}">
Upvotes: 3
Reputation: 921
Directly from the jQuery documentation
$("input[type='text']").change( function() {
// check input ($(this).val()) for validity here
});
Upvotes: 4
Reputation: 1746
You can save value of input on focus, and check it with value from input on blur.
Upvotes: 1
Reputation: 2376
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.
Upvotes: 6
Reputation: 1038800
Subscribe for .change()
instead of .blur()
. This way you will know that the value has changed.
Upvotes: 6