views:

439

answers:

2

Anyone that can help me out will be very much appreciated. I seem to have got myself into a bit of a kerfuffle.

I'm trying to assign response data - retrieved from an AJAX request using the jquery.autocomplete plugin - to an input element. I can get the response data back fine, but when I try and insert it into the 'value' attribute, nothing happens!

$('#btnPopulate').click(function() {
if ($('#list_length').val() != '') {
 var length = $('#list_length').val();
 var row='';
 for (var i=0; i <= length; i++) {
  row="<tr><td>"+i+"</td><td><input name='data[CompanyRanking]["+i+
   "][company_id]' id='CompanyRanking"+i+
   "CompanyId' value='1'></td><input type='hidden' name='data[CompanyRanking]["+i+
   "][ranking]' id='CompanyRanking"+i+"Ranking' value='"+i+"'></tr>";
  $('#ranking_table').append(row);
  $("CompanyRanking"+i+"CompanyId").autocomplete({ 
   serviceUrl:'/backend/companies/search',
   minChars:2, 
   delimiter: null, // regex or character
   maxHeight:400,
   width:300,
   deferRequestBy: 50, //miliseconds
   // callback function:
   onSelect: function(value, data){ 
       alert('You selected: ' + value + ', ' + data); 
                                $('#CompanyRanking'+i+'CompanyId').val(data);
       alert('val: '+
                             $('#CompanyRanking'+i+
                             'CompanyId').val() + 'object?: '+
                             $('#CompanyRanking'+i+'CompanyId'));
         }
  });
            };
 //$('#btnPopulate').ac;
    } else {
 alert('You must first specify how many companies are in the list.');
};
    return false;
});
+2  A: 

It seems as though you are trying to alert a text value and not the value itself.

alert('val: '+$('#CompanyRanking'+i+'CompanyId').text() + 'object?: '+$('#CompanyRanking'+i+'CompanyId'));

could perhaps be changed to:

alert('val: '+$('#CompanyRanking'+i+'CompanyId').val() + 'object?: '+$('#CompanyRanking'+i+'CompanyId'));
cballou
Thanks for the reply. I've also tried that. The .val() still returns 'undefined'. I've updated the original post so that it makes more sense.
gomezuk
+2  A: 

It would seem to be a problem of scope. Try creating a closure around the value of i inside the loop:

onSelect: (function(i) {
    return function(value, data){ 
        $('#CompanyRanking'+i+'CompanyId').val(data);
    }
}(i))

A better explanation can be found in this answer:

The problem you have here is that the variable item changes with each loop. When you are referencing item at some later point, the last value it held is used. You can use a technique called a closure (essentially a function that returns a function) to quickly scope the variable differently.

Crescent Fresh
THANK YOU! You saved me a lot of frustration.
gomezuk