简体   繁体   中英

Dependent multiselect dropdown using chosen and select2 plugins

This is the code I have written in View :

   <div class="col-lg-12" style="margin-bottom: 20px;">
    <div class="form-group">
        <label class="col-sm-3 control-label" style=" margin-top: 14px; ">Domains&nbsp;<font size="3" color="red">*</font></label>
        <br />

        <div class="col-sm-4" style="width:50%;">
            @Html.ListBoxFor(m => m.SelectedDomains, Model.AllDomains,
         new { @class = "chosen", multiple = "multiple", id = "drpDomains", style = "width: 350px;",onchange="FillDomain();" })
        </div>
    </div>
</div>




<div class="col-lg-12" style="margin-bottom: 20px;">
    <div class="form-group">
        <label class="col-sm-3 control-label" style=" margin-top: 14px; ">Domains new categories&nbsp;<font size="3" color="red">*</font></label>
        <br />

        <div class="col-sm-4" style="width:50%;">
            @Html.ListBoxFor(m => m.SelectedDomainCategories, Enumerable.Empty<SelectListItem>(),
           new { @class = "select2", multiple = "multiple", id = "multidomaincategory", style = "width: 350px;" })
        </div>
    </div>
</div>

<link href="~/Scripts/MultiSelect/chosen.css" rel="stylesheet" />

For Domains, I have used Chosen plugin, and for categories, i have used select2 plugin

 <script type="text/javascript">
$(".chosen-deselect").chosen({ allow_single_deselect: true });
$(".chosen").chosen().change();
$(".chosen").trigger('liszt:updated');
</script>

<script>
    function FillDomain() {
        $("#drpDomains option[value='']").removeAttr("selected");

        var selectArr = [];
        $('#drpDomains').each(function () {

            selectArr.push($(this).val());
        });
        var a = JSON.stringify(selectArr);

        var reference = this;
        $.ajax({
            url: @Url.Content("~/MyTemplate2/FillIndustry1"), //FillIndustry1 is a method in Controller
            type: "POST",
            dataType: "JSON",
            data: { Domain: a },
            success: function (DomainCategories) {

                $("#multidomaincategory").html("");

                $("#multidomaincategory").removeAttr("selected");
                var s = JSON.stringify(DomainCategories);

                var t = JSON.parse(s);

                for (var key in t) {

                    $("#multidomaincategory").append("<option value=" + t[key]["Value"] + ">" + t[key]["Text"] + "</option>");
                } 

            },
            error: function (data) {
                alert("failure error" + data);
                var t = window.JSON.parse(data.d);
                alert("failueee" + t);
            }

        });
       //I'm trying to remove all the selected items from dependent dropdown (#multidomaincategory) when all items from Domains(#drpDomains) are cleared

        if ($("#drpDomains").val() == null || $("#drpDomains").val() == "") {

            $("#multidomaincategory").removeAttr("selected");
            $("#multidomaincategory").css('display', 'none');



           }
    }
</script>

Controller :

[HttpPost]
    public ActionResult FillIndustry1(string Domain)
    {
        JArray jsonMembersArr = (JArray)JsonConvert.DeserializeObject(Domain);//convert SymptomString from json string to array

        ProfessionalTrans objprofessionaltrans = new ProfessionalTrans();
        string listdomains = "";
        foreach (var a in jsonMembersArr)
        {

            listdomains = string.Join(",", a);
        }
        var DomainCategories = objprofessionaltrans.GetDepCategories(listdomains);

        return Json(DomainCategories.ToList());
    }

Data Access Layer(Transaction):

public IEnumerable<SelectListItem> GetDepCategories(string domains)
    {
 //GetDepCategories method - To get categories based on Domains
        PTS_CommonEntities objentity = new PTS_CommonEntities();
        List<SelectListItem> allskills = new List<SelectListItem>();

        List<GetCatListbasedDomain> catnames = objentity.usp_GetCatListBasedOnDomains(domains).ToList();

        foreach (var it in catnames)
        {
            allskills.Add(new SelectListItem { Value = it.CategoryID.ToString(), Text = it.CategoryName });

        }    

        return allskills.AsEnumerable();

}

When I am clearing(closing) the selected items in Domains, the respective Categories are cleared from list, but not in the text box

Image Before Clearing

Image After Clearing the Domains

As you can see, the list is being cleared, but the selected items are still being shown in the UI.

Can someone please find out why the items are being displayed even after clearing them???

Because you are trying to clear the wrong element. #multidomaincategory is the select2 list that holds all of the values, there is a dynamic span class that gets rendered to the page right after this element, look at the html that select2 produces in your browser. Try:

$('#multidomaincategory').next().find('li').html('');

They are cleared from the list because $("#multidomaincategory").html(""); clears the html of the list of categories, not the rendered text elements in the text box.

Although a better way: $('#multidomaincategory').select2('data', null)

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