Search code examples
jqueryjquery-tokeninput

jQuery Tokeninput save combination of ID and secound Value as internal ID


I get an JSON Array like this:

[{"type":"user","id":"12","name":"Name of User"},{"type":"group","id":"9","name":"Name of UserGroup"}]

The Backend returns an JSON Array with Name, Id and the Type (User or Group).

Is there any way to manipulate the id before there is inputted to the input field, for example to

 type+"_"+id

?

Actually, I'm using this to intializie tokenInput:

$("input#id").tokenInput(apiURL+"search.php", {
                defaultValue:"User or User Group",
                hintText:"Fill in User or User Group name.",
                noResultsText:"nothing found.",
                searchingText:"Searching...",
                queryParam:"search",
                crossDomain:false,
                tokenLimit:5,
                preventDuplicates:true,
                minChars:3,
                resultsFormatter:function(item) {
                    return "<li><img src="+((item.type=="user") ? "contact" : "contact_group")+ ".png\"/>"+item.name+"</li>";
                }
            });

With the help of Rory McCrossan I got it work. Change the id into the resultsFormatter Method will do the trick:

resultsFormatter:function(item) {
     if (item.id.indexOf("_") == -1)
     {
           item.id = item.type+"_"+item.id;
     }

     return "<li><img src="+((item.type=="user") ? "contact" : "contact_group")+ ".png\"/>"+item.name+"</li>";

}

The "if (item.id.indexOf (...))" is nessecary, because the tokenInput chaches the entries, and if you search for the same string, the id already have the type+"_" prefix and would get it a secound/third/... time.


Solution

  • Try this:

    resultsFormatter: function(item) {
        var itemId = item.type + "_" + item.id;
        return "<li id='" + itemId + "'><img src="+((item.type=="user") ? "contact" : "contact_group")+ ".png\"/>"+item.name+"</li>";
    }