jQuery tag-it only allow available tags
Asked Answered
P

2

9

i use jQuery tag-it in my script:

$("#user_autocomplete").tagit({
    tagSource: function (request, response) {
        $.ajax({
            data: {
                term: request.term
            },
            type: "POST",
            url: "/site2/message/users.php",
            dataType: "json",
            success: function (data) {
                response($.map(data, function (item) {
                    return {
                        label: item,
                        value: item
                    }
                }));
            }
        });
    },
    tagLimit: 3,
    autocomplete: {
        delay: 0,
        minLength: 1
    },
});

In this case, all input fields are confirmed. But I want only the fields that are available to be added. How to do it?

Perforated answered 8/12, 2013 at 9:27 Comment(2)
Can you explain more? What you mean by "only fields that are available"?Creath
Thanks for adding your own solution. I've moved it to an answer; if you wish to offer a solution to your own question in the future, it is best to self-answer like this.Jailer
J
13

Posted on behalf of OP:

I'm using the beforeTagAdded function I found my answer:

        tagSource: function(request, response) 
        {
            $.ajax({
                data: { term:request.term },
                type: "POST",
                url:        "/site2/message/users.php",
                dataType:   "json",
                 success: function( data ) {
                     array = data;
                    response( $.map( data, function( item ) {

                        return {
                            label:item,
                            value: item
                        }
                        }));
                    }

            });
            },
        tagLimit :3,
        autocomplete: {delay: 0, minLength: 1},
        beforeTagAdded: function(event, ui) {
            if(array.indexOf(ui.tagLabel) == -1)
            {
                return false;
            }
            if(ui.tagLabel == "not found")
            {
                return false;
            }

        },
Jailer answered 8/12, 2013 at 9:27 Comment(2)
@Kakitori: I just posted it on behalf of the OP - maybe consider upvoting the original post if you liked it?Jailer
Thank you for sharing this piece of happiness (did upvote original post ;) )! You should consider make a pull request to the original project :)Squab
P
0

I was able to achieve this by adding the following check to the top of the createTag function:

if (this.options.onlyAvailableTags && $.inArray(this._formatStr(value), this.options.availableTags) == -1) {
    return false;
}

And then adding this option in the tag-it call:

onlyAvailableTags: true
Provocation answered 3/8, 2017 at 0:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.