Gaurang Joshi
Gaurang Joshi

Reputation: 695

Select2 - Can not select ajax result (not clickable)

I have used select2 jquery library, below code i did for seleting multiple users by ajax. I can search and i got the result of users but i can't select (it's not clickable) please have look what i did wrong.

HTML CODE

<select id="userSearch" name="users[]" class="txt-theme form-control" style="width:200px" placeholder="Search users..."></select>

JQUERY CODE

$('#userSearch').hide();
$("#userSearch").select2({
  ajax: {
    url: "http://localhost:8000/api/users",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        name: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, page) {
      // parse the results into the format expected by Select2.
      // since we are using custom formatting functions we do not need to
      // alter the remote JSON data
      return {
        results: data.items
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; },
  multiple: true,
  allowClear: true,
  placeholder: 'Share file(s) with...',
  minimumInputLength: 3,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection

});

function formatRepo(repo) {
  if (repo.loading) return repo.name;
  var markup = '<li value='+repo.user_id+'>'+repo.name+'</li>';
  return markup;
}

function formatRepoSelection (repo) {
  return repo.name || repo.name;
}

Thanks for help :)

Upvotes: 1

Views: 985

Answers (1)

Gaurang Joshi
Gaurang Joshi

Reputation: 695

Thank you all for try to find something for me. I got right answer by googling

Problem in this part

function formatRepo(repo) {
  if (repo.loading) return repo.name;
  var markup = '<li value='+repo.user_id+'>'+repo.name+'</li>';
  return markup;
}

I have to change from repo.user_id to repo.id because select2 library needs id as key to make selection selectable.

Thanks

Upvotes: 3

Related Questions