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

$('input[type="text"].js_test').liveSearch(successCallBackFn);
on any
input[type='text']
and the data received from the
$.ajax()
call is being handeled by
successCallBackFn()
. 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() {
$('.js_test').liveSearch(mySuccessCallback);
});

//callback
function mySuccessCallback($liveSearchTrigger, response) {
$('body').append(response.results_html);
}

//jQuery plugin
(function( $ ) {

$.fn.liveSearch = function(successCallbackFn) {

var $liveSearchTrigger = $(this);

$liveSearchTrigger.change(function() {
$.ajax({
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
POST
is being processed and the data in
response.results_html
is being appended to the
$('body')
element.

When I add

$('.js_test').change(function() {
console.log($(this).val());
});


to the
$(document).ready()
function's scope, any change is being registered instantly.

Why is the
POST
and its resulting
$('body').append()
only triggered after I refocus the browser window (by clicking into it) and how do I achieve that the
$liveSearchTrigger.change()
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: https://api.jquery.com/change/

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: https://api.jquery.com/keypress/

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