Following this question jquery autocomplete with more items in the same fields I was trying to loop the autocomplete function 15 times.
$(function() {
for (
Your code cannot work because you met a typical closure problem.
When you execute your code, the loop:
for (i = 0; i < 15; i++) {
has been completed before any of the autocomplete functions will run for the first time. This means that all your autocomplete functions will contain as variable i the value 15, and this is your problem. You may verify this right debugging your code.
A classical example of closure is:
for (var i = 1; i <= 5; i++) {
setTimeout(function() { console.log(i); }, 1000*i); // result: 6 6 6 6 6
}
How to avoid this? One of the possible solutions consist of using the IIFE. From MDN: IIFE (immediately invoked function expressions): is a JavaScript function that runs as soon as it is defined.
So in your case you can change a bit your code so that (I rewrote only the part of your interest):
var townTags = [
{label: 'Miami', value: 'Miami', state: 'Florida', country: 'Florida'},
{label: 'Rome', value: 'Rome', state: 'Italy', country: 'Italy'},
{label: 'Paris', value: 'Paris', state: 'France', country: 'France'},
{label: 'Berlin', value: 'Berlin', state: 'Germany', country: 'Germany'}
];
$(function () {
for (i = 0; i < 15; i++) {
(function(i) { // start IIFE
$('#town2' + i).autocomplete({
source: townTags,
select: function (event, ui) {
var item = ui.item;
if (item) {
$("#country2" + i).val(item.country);
$(this).val(item.value + ' is in ' + item.state);
return false;
}
}
});
})(i); // end IIFE
}
});