[EXTENSION] Echosen jQuery PLugin

I had this problem: I’m developing a similar-blog system and I wanted to implement echosen jquery plugin (so cool…) for the category / tag part. Problem is, for the kind of database structure I chose I had to retrieve only one value at the time via an ajax command triggered by .chosen().change(). Fair enough, this awesome plugin returned only an array of comma-separated values of ALL the option selected.

So I wanted to share a piece of javascript code that may be useful. I have




<select class="categories blabla..."></select>



and the function is:





$(function() {

        console.log('ready');

        var startValues = new String($('select.categories').chosen().val());

        var startArray = startValues.split(',');

        $('select.categories').chosen().change(function(){

            var newValues = $(this).chosen().val()+',';

            newValues = newValues.substring(0, newValues.length - 1);

            var newArray =newValues.split(',');

            compareArrays(startArray,newArray, 'update');

            compareArrays(newArray,startArray, 'delete');

            startArray = newArray;

        });

    });

    function compareArrays(x,y, mode)

    {

        var z = {};

        for (var j in x) {

            z[x[j]] = x[j];

        }

        for (var i in y) {

            if (typeof z[y[i]] == 'undefined') {

                console.log(mode +' ' + y[i]);

                //break;

            }

        }

    }

If you watch the console log you will see the value that has to be created or deleted. Of course instead of the "console.log" you may put an ajax trigger or something like that.

Hope that will be useful to somebody.