简体   繁体   中英

Set selected value on select2 without loosing ajax

I have this select2 code in my html (mvc with razor) page:

$('#QuickSearchState').select2({
            minimumInputLength: 3,
            width: 'resolve',
            ajax: {
                url: '@Url.Action("QuickSearchState", "DataCenter")',
                contentType: 'application/json',
                dataType: 'json',
                type: 'POST',
                traditional: true,
                quietMillis: 400,
                data: function(term, page) {
                    var data = {
                        term: term
                    };
                    return data;
                },
                results: function(data, page) {
                    return { results: data };
                }
            },
            initSelection: function(element, callback) {
                var data = { id: element.val(), text: element.val() };
                callback(data);
            },
            formatResult: function(format) {
                return format.label;
            },
            formatSelection: function(format) {
                //this is a knockout view model
                vmNewAddress.IdState(format.id);
                vmNewAddress.StateName(format.stateName);
                return format.label;
            },
            dropdownCssClass: "bigdrop",
            escapeMarkup: function(m) { return m; }
        });

But i have another select in my code that can set a state in this select, but i dont know how to set this value to that select.

In my html i have this:

<select class="width-xl" data-bind="options: vm.GivenLocationsForConnection, optionsText: 'DisplayFormat', value: SelectedLocation"></select> -> first select that can fill the second state search select with a state

@Html.Hidden("query", null, new { @id = "QuickSearchState", @class = "width-xl", placeholder = "Ej. Montevideo" }) -> second select, this is a search for states and selects a single state

我不确定这是否是您想要的,但是如果您只想在选择中选择一个值,则可以执行以下操作

$("#QuickSearchState").select2("val", "<YOUR VALUE>");

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