codeispoetry
codeispoetry

Reputation: 373

loop jquery autocomplete (second field)

Following this question jquery autocomplete with more items in the same fields I was trying to loop the autocomplete function 15 times.

 $(function() {
   for (i = 0; i < 15; i++) {   
      function log( message ) {
        $( "<div>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 1 );
      }

      $( "#town2"+i ).autocomplete({
         source: "<?php echo $absolute_site . "autocomplete/autocompletetown.php" ?>",
         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;                   
            }    
         }
      })
     .autocomplete( "instance" )._renderItem = function( ul, item ) {
        return $( "<li>" )
          .append( "<a>" +item.value + "," +item.state + "," + item.country + "</a>" )
          .appendTo( ul ); 
     };
  }
});

It autocompletes the #town21, #town22, #town23.... fields, but it doesn't autocomplete the #country21, #country22 .... fields. My for loop is probably in the wrong place...? Thanks!

Upvotes: 1

Views: 906

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

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
  }
});
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>


<div class="ui-widget">
    <label for="town20">Town: </label>
    <input id="town20">
    <label for="country20">Country: </label>
    <input id="country20"><br>
    <label for="town21">Town: </label>
    <input id="town21">
    <label for="country21">Country: </label>
    <input id="country21"><br>
    <label for="town22">Town: </label>
    <input id="town22">
    <label for="country22">Country: </label>
    <input id="country22"><br>
    <label for="town23">Town: </label>
    <input id="town23">
    <label for="country23">Country: </label>
    <input id="country23"><br>
    <label for="town24">Town: </label>
    <input id="town24">
    <label for="country24">Country: </label>
    <input id="country24"><br>
    <label for="town25">Town: </label>
    <input id="town25">
    <label for="country25">Country: </label>
    <input id="country25"><br>
</div>

Upvotes: 2

Related Questions