简体   繁体   中英

Set Select2 Dropdown value on other Select2 Dropdown change event

I am trying to Set Select2 Dropdown value on other Select2 Dropdown change event ..

These are My Dropdowns

<div >
        @Html.DropDownList(Model.deptProp, new SelectList(Bmsa.UI.Utility.Utility.GetAllDepartments(Model.countryCode), "Value", "Text", Model.deptId), new { onchange = "Getarrnds();" })

</div>

and

 <div>
                @Html.DropDownList(Model.cmnlSctnProp, new SelectList(Bmsa.UI.Utility.Utility.GetCmnlSection(Model.countryCode, Model.deptId, Model.arrndsId, Model.communeId), "Value", "Text", Model.cmnlSctnId))

        </div>

Script

<script type="text/javascript">
    $(function () {

        var $ddlSub = $("select[name$=deptId]");
        $ddlSub.select2();

        var $ddlcmnlSctn = $("select[name$=cmnlSctnId]");
        $ddlcmnlSctn.select2();

    });

</script>

this is parsed HTML for both dropdowns

<span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-deptId-container"><span class="select2-selection__rendered" id="select2-deptId-container" title="Select below">Select below</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span>

<span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-cmnlSctnId-container"><span class="select2-selection__rendered" id="select2-cmnlSctnId-container" title="Select below">Select below</span><span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span></span>

I have Tried following but these are not working

 $("select[name$=cmnlSctnId]").change(function () {
            $("select[name$=deptId]").select2("val","Ouest").val('Ouest').trigger("change");

$("select[name$=deptId]").select2("val","Ouest").val('2').trigger("change");

$("select[name$=deptId]").select2("val", "Ouest"); 

            $("select[name$=deptId]").val("2").trigger("change");
 $('select[name$=deptId]').select2('data', { id: 100, a_key: 'Lorem Ipsum' });
 $('select').select2().select2('val', $('.select2 option:eq(3)').val());

        });

.. How can I check where I am missing something ?

You need to attach click event as follows and use val method to set value

For Ex

var e1 = $("select[name$=deptId]").select2();

var e2 = $("select[name$=cmnlSctnId]").select2();

e1.on("click", function () { alert("test"); e2.val("2").trigger("change"); });

Please check the JSFiddle for select2 selection https://jsfiddle.net/6ncs0vvh/

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