Using jQuery i would like to run a function when either .change()
or .keyup()
are raised.
Something like this.
if ( jQuery(':input').change() || jQuery(':input').keyup() ) { alert( 'something happened!' ); }
EDIT
Sorry i forgot to mention. Both .change()
and .keyup()
need some of the variables to be in-scope.
jQuery keyup() Method The order of events related to the keyup event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.
The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus.
keyup / keydown seem to only work on elements that are present at document. ready . If you are triggering your event from elements that were altered or injected post pageload, these events will not fire.
The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress . An uppercase "A" is reported as 65 by all events.
you can bind to multiple events by separating them with a space:
$(":input").on("keyup change", function(e) { // do stuff! })
docs here.
hope that helps. cheers!
If you're ever dynamically generating page content or loading content through AJAX, the following example is really the way you should go:
body
of the document, so regardless of what elements are added, moved, removed and re-added, all descendants of body
matching the selector specified will retain proper binding.The Code:
// Define the element we wish to bind to. var bind_to = ':input'; // Prevent double-binding. $(document.body).off('change', bind_to); // Bind the event to all body descendants matching the "bind_to" selector. $(document.body).on('change keyup', bind_to, function(event) { alert('something happened!'); });
Please notice! I'm making use of $.on()
and $.off()
rather than other methods for several reasons:
$.live()
and $.die()
are deprecated and have been omitted from more recent versions of jQuery.$.change()
and $.keyup()
separately, or pass the same function declaration to each function called; Duplicating logic... Which is absolutely unacceptable.$.bind()
does not dynamically bind to elements as they are created. Therefore if you bind to :input
and then add an input to the DOM, that bind method is not attached to the new input. You'd then need to explicitly un-bind and then re-bind to all elements in the DOM (otherwise you'll end up with binds being duplicated). This process would need to be repeated each time an input was added to the DOM.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With