简体   繁体   中英

JQuery to get the last changed value from @Html.DropDownListFor asp.net mvc multiselect dropdownlistbox

How do I use Jquery to find the last checked/unchecked item and so that I can add or remove them from other two listboxs?

I am creating a dropdown listbox(excludedPeople) with multiselect checkbox with two other listboxs(PrimaryPerson,secondaryPerson) in same form. All three list box are having same set of data during form load. If any item in excludedPeople is selected(checked), I need to remove that item from PrimaryPerson and secondaryPerson and vise-versa.

ASP.Net MVC multiselect Dropdown Listbox code:

 @Html.ListBoxFor(m => m.ExcludedPeople, Model.AllPeopleListViewModel,
                        new { @class = "chkDrpDnExPeople" , @multiple = "multiple"})

jQuery code:

$(".chkDrpDnExPln").change(function ()
        {
            console.log("Trigger" + $(this).val()); //this code gets the list of all items selected. What I need is to log only last selected/unselected item's val & text into the console.
        });

Any help is appreciated. Ask questions if any.

Well, after waiting for 2 days I made a solution myself and posting it here so that others can make use of it.

I made this code for multiselect dropdown listbox with checkboxes in each list item. I expect this to work on similar controls like checked listbox but haven't tested it.

I followed register control and get notified by event so the usage can be made seamless without getting into details.

Usage:

1) include the "JQuery based Library" part into your project as shared or same js script file.

2) Use the below approach to consume the functionality. The event should get you the changed values when the control selection is changed.

RegisterSelectedItemChangeEvent("chkDrpDnctrl#1");
RegisterSelectedItemChangeEvent("chkDrpDnctrl#2");
RegisterSelectedItemChangeEvent("chkDrpDnctrl#3");

$(".chkDrpDnctrl").on("OnSelectionChange", function (e,eventData)
        {
            var evntArgs = {
                IsDeleted: false,
                IsAdded: false,
                AddedValues: [], //null if no change/None. Else changed value.
                DeletedValues: [] //null if no change/None. Else changed value.
            };
            var source = e;
            evntArgs = eventData;
            var elementnm = $(this).attr("id");
            if (evntArgs !== "undefined" && elementnm != "")
            {
                if (evntArgs.IsAdded == true)
                {
                    //if excluded checked then remove.
                    for (var i = 0; i < evntArgs.AddedValues.length; i++)
                    {
                        PerformAction (control#, evntArgs.AddedValues[i]);
                    }
                }
                if (evntArgs.IsDeleted == true)
                {
                    //if excluded checked then remove.
                    for (var i = 0; i < evntArgs.DeletedValues.length; i++)
                    {
                        PerformAction (control#, evntArgs.AddedValues[i]);                    
                  }
                }
            }
        });

JQuery based Library:

 function RegisterSelectedItemChangeEvent(selector) {
    var dropdownElementRef = selector;
    //Intializes the first time data and stores the values back to control. So if any of the checkboxes in dropdown is selected then it will be processe and added to control.
    $(dropdownElementRef).data('lastsel', $(dropdownElementRef).val());
    var beforeval = $(dropdownElementRef).data('lastsel');
    var afterval = $(dropdownElementRef).val();
    //storing the last value for next time change.
    $(dropdownElementRef).data('lastsel', afterval);
    //get changes details
    var delta = GetWhatChanged(beforeval, afterval);
    //stores the change details back into same object so that it can be used from anywhere regarless of who is calling it.
    $(dropdownElementRef).data('SelectionChangeEventArgs', delta);
    //prepares the event so that the same operation can be done everytime the object is changed.
    $(dropdownElementRef).change(function () {
        var beforeval = $(dropdownElementRef).data('lastsel');
        var afterval = $(dropdownElementRef).val();
        //storing the last value for next time change.
        $(dropdownElementRef).data('lastsel', afterval);
        //get changes details
        var delta = GetWhatChanged(beforeval, afterval);
        //stores the change details into same object so that it can be used from anywhere regarless of who is calling it.
        $(dropdownElementRef).data('OnSelectionChangeEventArgs', delta);
        //fires the event
        $(dropdownElementRef).trigger('OnSelectionChange', [delta]);
        //$.event.trigger('OnSelectionChange', [delta]);
    });
    var initdummy = [];
    var firstval = GetWhatChanged(initdummy, afterval);
    //fires the event to enable or disable the control on load itself based on current selection
    $(dropdownElementRef).trigger('OnSelectionChange', [firstval]);
}


//assume this will never be called with both added and removed at same time.
//console.log(GetWhatChanged("39,96,121,107", "39,96,106,107,109")); //This will not work correctly since there are values added and removed at same time.
function GetWhatChanged(lastVals, currentVals)
{
    if (typeof lastVals === 'undefined')
        lastVals = '' //for the first time the last val will be empty in that case make both same. 
    if (typeof currentVals === 'undefined')
        currentVals = ''
    var ret = {
        IsDeleted: false,
        IsAdded: false,
        AddedValues: [], //null if no change/None. Else changed value.
        DeletedValues: [] //null if no change/None. Else changed value.
    };
    var addedvals;
    var delvals;
    var lastValsArr, currentValsArr;
    if (Array.isArray(lastVals))
        lastValsArr = lastVals;
    else
        lastValsArr = lastVals.split(",");
    if (Array.isArray(currentVals))
        currentValsArr = currentVals;
    else
        currentValsArr = currentVals.split(",");
    delvals = $(lastValsArr).not(currentValsArr).get();
    if (delvals.length > 0)
    {
        //console.log("Deleted :" + delvals[0]);
        for (var i = 0; i < delvals.length; i++)
        {
            ret.DeletedValues.push(delvals[i]);
        }
        ret.IsDeleted = true;
    }
    addedvals = $(currentValsArr).not(lastValsArr).get();
    if (addedvals.length > 0)
    {
        //console.log("Added:" + addedvals[0]);
        for (var i = 0; i < addedvals.length; i++)
        {
            ret.AddedValues.push(addedvals[i]);
        }
        ret.IsAdded = true;
    }
    return ret;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM