Monday, January 21, 2013

Implementing setOptions() function in jQuery Tokeninput

Thanks James Smith for a great jQuery plugin, jQuery Tokeninput

What is jQuery Tokeninput?

A jQuery plugin which allows you to select/search multiple items from a predefined JSON object list, using auto-completion as you type to find each item on a specific JSON object attribute. You may have seen a similar type of text entry in Facebook when filling in the recipients field during sending message.

See demos here http://loopj.com/jquery-tokeninput/demo.html
See options here http://loopj.com/jquery-tokeninput/#configuration

Why we need setOptions() function?

In jQuery Tokeninput the most important option is propertyToSearch (The javascript/json object attribute to search. default: “name”), which was not changeable before implementing setOptions() function.

While using jQuery Tokeninput I realized that if there is an option to change propertyToSearch at any-time that might be very useful. Then I started implementing setOptions() function in jQuery Tokeninput.
Following example shows that we can change propertyToSearch and hintText at any-time we want, using setOptions() function:


    $(document).ready(function() {
        $(element).tokenInput([{
                    "first_name": "Arthur",
                    "last_name": "Godfrey",
                    "email": "arthur_godfrey@nccu.edu",
                    "url": "https://si0.twimg.com/sticky/default_profile_images/
                },
                {
                    "first_name": "Adam",
                    "last_name": "Johnson",
                    "email": "wravo@yahoo.com",
                    "url": "https://si0.twimg.com/sticky/default_profile_images/
                }], {propertyToSearch: "first_name"}
        );
    });


Later we can do followings at any time


$(element).tokenInput("setOptions", {propertyToSearch: 'first_name', hintText: "Type first name here to search"});
$(element).tokenInput("setOptions", {propertyToSearch: 'last_name', hintText: "Type last name here to search"});
$(element).tokenInput("setOptions", {propertyToSearch: 'email', hintText: "Type email here to search"});
$(element).tokenInput("setOptions", {propertyToSearch: 'url', hintText: "Type url here to search"});

You can see that now we can change propertyToSearch at any-time

You will find latest updates in Github project page https://github.com/loopj/jquery-tokeninput and checkout https://github.com/loopj/jquery-tokeninput/blob/master/demo.html file for demo of setOptions() function in Change propertyToSearch anytime section


1 comment:

  1. I'm trying to assing onAdd function using the setOptions:
    $txtTokenInput.tokenInput("setOptions", {
    onAdd: function (item) {
    alert(1);
    }
    });

    but it's not working. Any sugestions?

    ReplyDelete