Reputation: 4267
I am building a search form and ajax function inside .keyup can have different arguments, I want to check if I need to include this arg by checking if another value exists. Here is what I have now:
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
if (GLOBAL_VARS['link_id']) {
search.keyup(function() {
delay(function() {
var query = search.val();
ajaxGet(GLOBAL_VARS.distributorsSearchDistUrl, {
'query': query,
'pk' : GLOBAL_VARS['link_id']
}, function(content) {
$('#distributors').html(content);
set_favorite();
});
}, 500);
});
} else {
search.keyup(function() {
delay(function() {
var query = search.val();
ajaxGet(GLOBAL_VARS.distributorsSearchDistUrl, {
'query': query
}, function(content) {
$('#distributors').html(content);
set_favorite();
});
}, 500);
});
}
HTML:
<div class="input-field col s6 right no-margin">
<input id="search" type="text" class="validate" name="search">
<label class="active" for="search">Search</label>
</div>
But this works for 1 time only, after I input any leter(a
for example a get):
search_dist?query=a&pk=64
but when I enter aa(second input) I get:
search_dist?query=aa
without pk
.
What am I doing wrong?
Upvotes: 0
Views: 35
Reputation: 1774
For starters, I would suggest putting your conditions inside the .keyup
callback. This will avoid the possibility of trying to bind the same event twice to the same element.
search.keyup(function() {
delay(function() {
var data = {
query: search.val();
}
if (GLOBAL_VARS['link_id']) {
data.pk = GLOBAL_VARS.link_id;
}
ajaxGet(GLOBAL_VARS.distributorsSearchDistUrl, data, function(content) {
$('#distributors').html(content);
set_favorite();
});
}, 500);
});
Working plnkr
Upvotes: 1