SweNz
SweNz

Reputation: 53

Set selected items on Select2 when page load (ASPX)

I google about 6 hrs., there are numbers of Select2 questions like this but I still stuck at this problem.

I want to show items that user selected before form submit after Page load.

jQuery 2.2.1, Select2 4.0.13

Markup

<select id="ddlMaterial" class="rbp-material-ddl" multiple="multiple" style="width: 100%"> </select>

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "RBP.aspx/GetOptionList",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var obj = JSON.parse(data.d);
                var s = '';
                ... make option group ...
                $('.rbp-material-ddl').html(s);
            }
        });

        $('.rbp-material-ddl').select2({
            closeOnSelect: false, allowClear: true
        })

        $('.rbp-material-ddl').val(<%=selectedList%>).trigger('change');
    });
</script>

selectedList is a variable that I stored user selection.

When I am debug while page loading, I got $('.rbp-material-ddl').val(['help','me','please']).trigger('change'); as it meant to be and it was executed but select2 shows nothing.

When I execute that command via Chrome DevTool after everything is loaded the select2 show 3 selection properly. :'(

I also tried following command and I have no luck.

$('.rbp-material-ddl').val(['please']);
$('.rbp-material-ddl').trigger('change');

Please give me some advice.

Thank you

Upvotes: 0

Views: 635

Answers (1)

SweNz
SweNz

Reputation: 53

I found that .. $ajax didn't success before select2.val() is fired.

I move that function to success callback and it works.

Upvotes: 1

Related Questions