Search code examples
jquery-select2-4

Add attributes to the selected list items in select2


Here is a working jsfiddle. I wish to add attributes (in particular id) to the <li> elements created. My use case is slightly different from the fiddle, rather than using an array, I am getting my data from ajax. In addition I want to give my users flexibility to create new tags if the same are not present in database. To save newly created item list having id's is a much better handle than just plain classes. Can I modify the attributes of the enter image description here<li> elements created?

My actual code is something like this:

$(".js-data-example-ajax").select2({
        ajax : {
            url : "/content/search_skills",
            dataType : 'json',
            delay : 250,
            data : function(params) {
                return {
                    q : params.term, // search term
                    page : params.page
                };
            },
            processResults : function(data, params) {
                params.page = params.page || 1;

                return {
                    results : data.items,
                    pagination : {
                        more : (params.page * 5) < data.total_count
                    }
                };
            },
            cache : true
        },
        escapeMarkup : function(markup) {
            return markup;
        }, // let our custom formatter work
        minimumInputLength : 1,
        templateResult : formatRepo,
        templateSelection : formatRepoSelection,
        tags : true,
        createTag : function (params) {
            return {
                id: params.term,
                text: params.term,
                newOption: true
              }
            },
    });
    function formatRepo(repo) {
        if (repo.loading)
            return repo.text;

        var markup = '<ul class="list-group clear-list m-t">' + '<li class="list-group-item fist-item"><span class="pull-right">' + repo.id + '</span> <span class="label label-success">' + repo.count + '</span> ' + repo.text + '</li>';

        return markup;
    }

     function formatRepoSelection (repo) {
         var markup = repo.text;
         return markup;
          }

And my jsp (html) is:

<select class="js-data-example-ajax" style="width: 100%" multiple="multiple">
    //Iterating through database query result to pre-load option items
    <option value="<%=skill_objective.get("id")%>" selected="selected"><%=skill_objective.get("id")%> <%=skill_objective.get("name") %></option>
</select>

Solution

  • Here is a working solution:

    $(".js-data-example-ajax").select2('data') will give me a hash of all the objects selected.