John Smith
John Smith

Reputation: 6259

Filter specific items in array

I use jquery tokeninput to fill my inputs with data from the server for example:

$(".input").tokenInput("http://shell.loopj.com/tokeninput/tvshows.php", {
            prePopulate: [{id: 123, name: "Slurms MacKenzie"}],
        });

So now i have the problem that i want to fill several input on a site with specific data, so i changed my code a little bit:

<input type="text" id="1" class="input" name="blah" />
<input type="text" id="2" class="input" name="blah" />

        var array =  [
            {id: 123, name: "Smith", input: "1"},
            {id: 156, name: "Kanye", input: "2"},
            {id: 134, name: "MacKenzie", input: "1"}
            ]

     $(".input").tokenInput("http://shell.loopj.com/tokeninput/tvshows.php", {
            prePopulate: array
        });

How you can see i added in the array input where the id od the input is defiend the item should be appendend to, for example:

 {id: 156, name: "Kanye", input: "2"}

Should be only assigend to input with id 2

So how can i filter only the entries of the array where $(this).attr("id") has the same value as input: in array?

Thanks fiddle: http://jsfiddle.net/v394w/7/

Upvotes: 0

Views: 73

Answers (1)

Andreas
Andreas

Reputation: 21881

Grab each .input, filter the array for the corresponding id with $.grep() and initialize tokenInput with the filtered array

var array =  [
    {id: 123, name: "Smith", input: "1"},
    {id: 156, name: "Kanye", input: "2"},
    {id: 134, name: "MacKenzie", input: "1"}
];

$(".input").each(function(_, item) {
    var filtered= $.grep(array, function(el) {
                        return el.input == item.id;
                    });

    $(this).tokenInput("http://shell.loopj.com/tokeninput/tvshows.php", {
        prePopulate: filtered
    });
});

fiddle

Upvotes: 1

Related Questions