Get the value and status (selected or not) of an option that fires a multiple onchange event

I want to get only value added / added value from selection instead of array with all selected values.

How can I control each individual parameter instead of the entire selector to see which one has changed?

I know I can compare the previous and current state of the entire selector, but that means keeping the previous state, and since this is not only one selector I want to keep track of, but an indefinite number of them (one per entry in the list of entries obtained from database), I'd really like to use an easier way to get the last selected / unselected value, if any.

Another alternative I just thought of: instead of keeping track of each state of the selector, using the onfocus event to save the state of the selector to be changed (but still I'd prefer a solution where I don't have to compare if there is one).

Current solution: use bootstrap multiselect jquery plugin onchange (bootstrap multiselect turns the selector into a list so that each parameter can be controlled individually using its own exchange event). Any "plugin" ideas?

+3


source to share


1 answer


I don't think there is any decent solution. Create your own jQuery plugin to compare abstract states.

Perhaps this little plugin that fires a custom event optionChange

on a list gives you two additional parameters (value, state):

$.fn.trackOptions = function(){
    return this.each(function(){
        var $select = $(this),
            oldItems = $select.val() || [];
        $select.data("oldItems", oldItems)
        .on("change", function(e){
            var oldItems = $select.data("oldItems"),
                newItems = $select.val() || [];
            for(var i=0; i<oldItems.length; ++i) {
                if(newItems.indexOf(oldItems[i]) == -1){
                    $select.trigger("optionChange", [oldItems[i], false]);
                }
            }
            for(i=0; i<newItems.length; ++i){
                if(oldItems.indexOf(newItems[i]) == -1){
                    $select.trigger("optionChange", [newItems[i], true]);
                }
            }
            $select.data("oldItems", newItems);
        });
    });
}

      



jsFiddle

If necessary, you can change it to trigger a single event with a list of deleted parameters.

+1


source







All Articles