Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery input value change detection

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?

like image 800
Yekver Avatar asked Nov 30 '22 07:11

Yekver


2 Answers

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

like image 82
Darin Dimitrov Avatar answered Dec 31 '22 12:12

Darin Dimitrov


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.

like image 33
Jemaclus Avatar answered Dec 31 '22 11:12

Jemaclus