Search code examples
jquery-select2jquery-select2-4

Trigger change and selection in select2 populated by ajax


I m populating my select2 using ajax with processResults function as in this code,

function PopulateSelect2(sqlclass, ControlID, PlaceHolder) {
$('#' + ControlID).select2({
    placeholder: PlaceHolder,
    allowClear: true,
    theme: "bootstrap",
    ajax: {
        type: "POST",
        url: "../Web_Services/Common/Controllers.asmx/populateCtls",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        //delay: 250,
        data: JSON.stringify({ selector: sqlclass, subselector: '' }),
        processResults: function (data) {
            var parsed = JSON.parse(data.d);
            console.log(parsed)
            return {
                results: parsed
            };
        }
    },
});}

and I call this function in this way,

$(document).ready(function () {
                PopulateSelect2("ddl_occupation", "AddrStateID", "Select")
            });

I am trying to set the value after by triggering change but its not working

I tried the following,

$('#AddrStateID').val(4).trigger('change.select2');

I managed to trigger selection inside the list but without showing the value in theselectelement control using this code

$("#AddrStateID").select2("trigger", "select", {
                    data: { id: "4" }
                })

is there a way to trigger the selection and show the result in the select control?


Solution

  • So in i worked around it by pre-populating my select control by ajax call but not by using select2 - ajax call

    I added the following attributes to each select control

    parent="" param="" child="" placeholder="" aval=""
    

    Where,

    parent: represents the parent id selector, param: represents the control's data parameter that I use for ajax call, child: represents the control's child control id selector, placeholder: represents the control's placeholder, aval: represents the control's assigned value in case wanted to be populated and selected because I use my form for storing data and reading data as well.

    in the following example I have 3 select cascade controls.

    <div class="panel-body">
                        <div class="col-xs-12">
                            <div class="form-grobtn row">
                                <label class="col-sm-2 col-form-label">File Grobtn</label>
                                <div class="col-sm-10">
                                    <select id="GpId" style="width: 100%"
                                        class="form-control populate" name="GpId" parent="" param="ddl_btnldgp" child="#CatId"
                                        placeholder="File Grobtn..."
                                        aval="">
                                        <option></option>
    
                                    </select>
                                </div>
                            </div>
                            <div class="form-grobtn row">
                                <label class="col-sm-2 col-form-label">File Category</label>
                                <div class="col-sm-10">
                                    <select id="CatId" style="width: 100%"
                                        class="form-control populate" name="CatId" parent="#GpId" param="ddl_btnldcat"
                                        placeholder="Select File Category..."
                                        child="#CatDtlId" aval="">
                                        <option></option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-grobtn row">
                                <label for="inputPassword3" class="col-sm-2 col-form-label">File Type</label>
                                <div class="col-sm-10">
                                    <select id="CatDtlId" style="width: 100%"
                                        class="form-control populate" parent="#CatId" param="ddl_btnldcatdtl" child=""
                                        placeholder="Select File Type..."
                                        aval="">
                                        <option></option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <button id="btn" class="btn cUpldBtn btn-success" type="button">
                        Assign</button>
    

    And Are being populated using this function

      function populateddl(ctl) {
    var $this = $(ctl);
    var parent, param, child, aval
    parent = $this.attr('parent');
    placeholder = $this.attr('placeholder');
    child = $this.attr('child');
    $(child).prop("disabled", true);
    param = $this.attr('param');
    aval = $this.attr('aval');
    if (!parent) {
        $.ajax({
            type: "POST",
            url: "../Web_Services/Common/Controllers.asmx/populateCtls",
            data: JSON.stringify(obj = {
                selector: param,
                subselector: null
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var jsonData = JSON.parse(data.d);
                $this.html('').append('<option>')
                $(child).prop("disabled", true)
                $this.select2({
                    data: jsonData,
                    placeholder: $this.attr('PlaceHolder'),
                    allowClear: true,
                    theme: "bootstrap"
                });
                if (aval) { $this.val(aval).trigger('change'); $this.attr('aval',''); }
            },
        })
    }
    $this.change(function () {
        if ($this.val() && child) {
            $.ajax({
                type: "POST",
                url: "../Web_Services/Common/Controllers.asmx/populateCtls",
                data: JSON.stringify(obj = {
                    selector: $(child).attr('param'),
                    subselector: $this.val()
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {                
                    var jsonData = JSON.parse(data.d);
                    $(child).html('').append('<option>')
                    $(child).prop("disabled", false)
                    $(child).select2({
                        data: jsonData,
                        placeholder: $(child).attr('PlaceHolder'),
                        allowClear: true,
                        theme: "bootstrap"
                    });
                    if ($(child).attr('aval')) { $(child).val($(child).attr('aval')).trigger('change'); $(child).attr('aval', ''); }
                },
            })
        } else {
            $(child).html('').append('<option>').prop("disabled", true).trigger('change');
        }
    })}
    

    Only parents (including childs that are parent to sub select controls) are called using function populateddl(ctl)

    in this example I populate as following,

    $(document).ready(function () {
            populateddl('#GpId');
            populateddl('#CatId');
        })
    

    In order to assign values, I need to populate and select the value afterwords for child controls,

    $(document).ready(function () {
            $("#btn").click(function () {
                $('#GpId').val(1).attr('aval', '1').trigger('change', 'select2');
                $('#CatId').val(2).attr('aval', '2').trigger('change', 'select2');
                $('#CatDtlId').val(1).attr('aval', '1').trigger('change', 'select2');
                return false;
            })
        })