phew phew - 3 years ago 163
Ajax Question

jQuery custom plugin 'change'-event is not being processed immediatly

I am trying to build a very lightweight live search as a jQuery custom plugin.

What I want to achieve is that I call

on any
and the data received from the
call is being handeled by
. In my test case I am simply adding it to the DOM.

<input class="js_test" type="text" name="test" value="" data-identifier="testajax" />

$(document).ready(function() {

function mySuccessCallback($liveSearchTrigger, response) {

//jQuery plugin
(function( $ ) {

$.fn.liveSearch = function(successCallbackFn) {

var $liveSearchTrigger = $(this);

$liveSearchTrigger.change(function() {
url: '/ajax/livesearch/' + $(this).data('identifier'),
type: 'POST',
dataType: 'JSON',
data: {
search: this.value
success: function(response) {
if (response.success) {
if (typeof(successCallbackFn) !== 'undefined') {
return successCallbackFn($liveSearchTrigger, response);

return this;

}( jQuery ));

Now when I type something into the input, nothing happens. (Firefox) Developer Tools show me that no XHR is taking place until I click the browser window again, then the
is being processed and the data in
is being appended to the

When I add

$('.js_test').change(function() {

to the
function's scope, any change is being registered instantly.

Why is the
and its resulting
only triggered after I refocus the browser window (by clicking into it) and how do I achieve that the
is being triggered instantly when typing into the input?

I am sure I am missing something very minor hence this is my first attempt in making a custom jQuery plugin.

Answer Source

The change event is only triggered when the element loses focus on text inputs.

I would recommend rereading:

And also change your call to .change() call to something like keypress() or keydown()

If you use those methods everytime a key is pressed within the input you can assume its value has changed and carry out your livesearch.

Keypress documentation here:

Note: For performance you will probably want to add in a check that the key pressed is not a modifier, ie. shift or escape

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download