Is it possible to bind javascript (jQuery is best) event to "change" form input value somehow?
I know about .change()
method, but it does not trigger until you (the cursor) leave(s) the input field. I have also considered using .keyup()
method but it reacts also on arrow keys and so on.
I need just trigger an action every time the text in the input changes, even if it's only one letter change.
You can also store the initial value in a data attribute and test it with the current value.
Would return true if the initial value has not changed.
here is the fiddle http://jsfiddle.net/Q9PqT/1/
You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):
This would work pretty good against a long list of items too. Using
jQuery.data
means you don't have to create a javascript variable to track the value. You could do$("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc")
to track many fields.UPDATE: Added
blur
to thebind
list.Since the user can go into the OS menu and select paste using their mouse, there is no safe event that will trigger this for you. The only way I found that always works is to have a setInterval that checks if the input value has changed:
You can also set this up using a jQuery special event.
Yes, compare it to the value it was before it changed.
Another option is to only trigger your changed function on certain keys. Use
e.KeyCode
to figure out what key was pressed.You can set events on a combination of key and mouse events, and onblur as well, to be sure. In that event, store the value of the input. In the next call, compare the current value with the lastly stored value. Only do your magic if it has actually changed.
To do this in a more or less clean way:
You can associate data with a DOM element (lookup api.jquery.com/jQuery.data ) So you can write a generic set of event handlers that are assigned to all elements in the form. Each event can pass the element it was triggered by to one generic function. That one function can add the old value to the data of the element. That way, you should be able to implement this as a generic piece of code that works on your whole form and every form you'll write from now on. :) And it will probably take no more than about 20 lines of code, I guess.
An example is in this fiddle: http://jsfiddle.net/zeEwX/