Reputation: 1849
I'm using this for my auto completes: http://jquery.bassistance.de/autocomplete/demo/
it's working just fine for normal inputs, for example:
$(".product_name").autocomplete('auto_complete.php', {
selectFirst: false,
extraParams: {
type: 'products_name',
lang: 'en',
},
width: '12%',
});
This works fine when I have the inputs with class product_name
on my page, but now in my new case I want to add the auto complete for some inputs which are not already on the page and they are just appended to the body using somethin like this:
$('#blah').on('click', function(){
$('.some_div').append('<input type="text" class="newly_added" />');
});
Normal auto complete initialize wont work for this input with class newly_added
, so I wrote:
$('body').on('focus', '.some_div input[type="text"]', function(){
$(".newly_added").autocomplete('auto_complete.php', {
selectFirst: false,
extraParams: {
type: 'products_name',
lang: 'en',
},
width: '12%',
});
});
This fixed the problem, now newly_added
will also have auto completes, but the problem is when I check the Ajax requests by Firebug, several ajax requests will be sent instead of just one! I mean for auto complete of each input more than 2,3,4 requests will be sent to the server, and the number of requests will be increased by adding more inputs to the page, sometimes even 20 requests will be sent.
So the question is, how I should prevent multiple requests for this? or is there any other way which works fine for this scenario?
Thanks
Upvotes: 0
Views: 725
Reputation: 74420
Use that instead and remove body focus handler:
$('#blah').on('click', function () {
$('.some_div').append('<input type="text" class="newly_added" />').find('.newly_added').filter(function () {
return !$(this).data('autocomplete')
}).autocomplete('auto_complete.php', {
selectFirst: false,
extraParams: {
type: 'products_name',
lang: 'en',
},
width: '12%'//, for support of old IE, you should remove this extra comma
});
});
There is maybe no need to add specific data to autocomplete as i think plugin already use some, so you could try to check for it.
UPDATE
just checked, autocomplete plugin already add specific data to element, so no need to add data, just the check is enough.
Upvotes: 1