Search code examples
javascriptjqueryat.js

Multiple object array not working in At.js


I'm using At.js plugin. It's working fine for a single object (demo)

var names1 = ["Jacob", "Isabella", "Ethan", "Emma", "Daniel", "Madison"];
var names = $.map(names1, function(value, i) {
  return {
    'id': i,
    'name': value,
    'email': value + '@yahoo.com'
  };
});

But when I try to add multiple objects it's not working (demo). I knew the code is the problem. I want to display the description when a user selects the name of the person using @ tag.

$(function() {
  $.fn.atwho.debug = true

  var names1 = [{
      "name": "Jacob",
      "description": "description one description one description one"
    },
    {
      "name": "Isabella",
      "description": "description two description two description two"
    }
  ];

  var names = $.map(names1, function(value, description, i) {
    return {
      'id': i,
      'name': value,
      'email': description
    };
  });

  var at_config = {
    at: "@",
    data: names,
    headerTpl: '<div class="atwho-header">Service List <small>↑&nbsp;↓&nbsp;</small></div>',
    insertTpl: '${email}',
    displayTpl: "<li>${name}</li>",
    limit: 200
  }
  $inputor = $('#inputor').atwho(at_config);
  $inputor.caret('pos', 47);
  $inputor.focus().atwho('run');
});

Solution

  • The map function in Jquery does not take each element in a object as the function argument, you get the entire object (the element in the list) and you then need to extract the name, and the description. You were almost there.

    $(function() {
      $.fn.atwho.debug = true
    
      var names1 = [{
          "name": "Jacob",
          "description": "description one description one description one"
        },
        {
          "name": "Isabella",
          "description": "description two description two description two"
        }
      ];
    
      var names = $.map(names1, function(value, index) { //Here I have only used value
        return {
          'id': index,
          'name': value.name, //Here I take value.name from the object
          'email': value.description //And value.description from the object
        };
      });
    
      var at_config = {
        at: "@",
        data: names,
        headerTpl: '<div class="atwho-header">Service List <small>↑&nbsp;↓&nbsp;</small></div>',
        insertTpl: '${email}',
        displayTpl: "<li>${name}</li>",
        limit: 200
      }
      $inputor = $('#inputor').atwho(at_config);
      $inputor.caret('pos', 47);
      $inputor.focus().atwho('run');
    });