0

I have following method which gets online agents and put them in auto complete, user clicks from the auto complete box to pickup the name. But on click its always taking the last name from the array: msg.db

enter image description here (click Roaxana or Roman, picks always Rubin) enter image description here

function ___________other_tasks(input) {
  switch(keyboard_mode) {
    case 'show_all_agents':

      $('#select_box_users').html('');

      $.post(submit_url + '/zendframework/agentslist', {
        firstname: $('#keyboard_input').val(),
      }, function(msg) {
        __cache = msg.db;

        for(_key in msg.db) { // Suppose i have 3 agents, on click each of them it only shows the last record value 

          let $clickme = $('<div class="agents_list">' + msg.db[_key].firstname + ' ' + msg.db[_key].lastname + '</div>');
          $clickme.click( () => click_agent_list(msg.db[_key].id, msg.db[_key].firstname, msg.db[_key].lastname ) );

          $('#select_box_users').append($clickme);

        }


      }, 'json');
    break;
  }
}


function click_agent_list(input, input1, input2) {
  alert(input1); // shows last value 
}

1 Answers1

0

You have to create closure in for loop.You can create closure by using let keyword before _key varibale.let implicitly introduces closures (actually scopes) for the variables declared with it.You can use let or IIFE to implement closure with in for loop.

    function ___________other_tasks(input) {
  switch(keyboard_mode) {
    case 'show_all_agents':

      $('#select_box_users').html('');

      $.post(submit_url + '/zendframework/agentslist', {
        firstname: $('#keyboard_input').val(),
      }, function(msg) {
        __cache = msg.db;

        for(let _key in msg.db) { // Suppose i have 3 agents, on click each of them it only shows the last record value 

          let $clickme = $('<div class="agents_list">' + msg.db[_key].firstname + ' ' + msg.db[_key].lastname + '</div>');
          $clickme.click( () => click_agent_list(msg.db[_key].id, msg.db[_key].firstname, msg.db[_key].lastname ) );

          $('#select_box_users').append($clickme);

        }


      }, 'json');
    break;
  }
}


function click_agent_list(input, input1, input2) {
  alert(input1); // shows last value 
}
Chinmoy Samanta
  • 1,376
  • 7
  • 17