简体   繁体   English

JQuery 从@Html.DropDownListFor asp.net mvc multiselect dropdownlistbox 获取最后更改的值

[英]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?如何使用 Jquery 找到最后一个选中/未选中的项目,以便我可以在其他两个列表框中添加或删除它们?

I am creating a dropdown listbox(excludedPeople) with multiselect checkbox with two other listboxs(PrimaryPerson,secondaryPerson) in same form.我正在创建一个带有多选复选框的下拉列表框(excludedPeople),其他两个列表框(PrimaryPerson,secondaryPerson)以相同的形式。 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.如果excludedPeople 中的任何项目被选中(选中),我需要从PrimaryPerson 和secondaryPerson 中删除该项目,反之亦然。

ASP.Net MVC multiselect Dropdown Listbox code: ASP.Net MVC 多选下拉列表框代码:

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

jQuery code: jQuery 代码:

$(".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.好吧,等了2天后,我自己做了一个解决方案,并在这里发布,以便其他人可以使用它。

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. 1)将“基于 JQuery 的库”部分作为共享或相同的 js 脚本文件包含到您的项目中。

2) Use the below approach to consume the functionality. 2)使用以下方法来使用功能。 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:基于 JQuery 的库:

 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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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