How to set select value in select2 plugin - jquery
Asked Answered
U

3

5

I use this code for insert data to select element with select2 plugin:

$.ajax({
    type: "POST",
    url: "ws.asmx/GetEvrakGrup",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (dc, status) {
        jsonData = JSON.parse(dc.d);
        $("#selectId").select2({
            data: jsonData
        });

    },
    error: function () { alert("This is an Error");}
});

After I want to set a value in this select but its not working:

$("#selectId").val(81);
Useless answered 10/8, 2016 at 12:31 Comment(0)
A
18

Try this :

$("#selectId").val(81).trigger('change');

Instead of

$("#selectId").val(81);
Amend answered 11/8, 2016 at 17:47 Comment(1)
No worries Huseyin, hope your project will be a huge success.Amend
F
6
$("#MyDropdownList").select2("trigger", "select", {
                        data: { id: theID, text: theText }
                    });
Fatal answered 27/10, 2019 at 2:20 Comment(1)
Please don't post only code as an answer, but also include an explanation what your code does and how it solves the problem of the question. Answers with an explanation are generally of higher quality, and are more likely to attract upvotes.Plotter
M
5

try below code:

var $example = $("#selectId").select2();
$example.val(81).trigger("change"); 
Manamanacle answered 10/8, 2016 at 12:37 Comment(3)
Hi @Prashant Patill, i take same result.Its not workingTabular
oh! have you checked select2 examples? please look in to it select2.github.io/examples.htmlManamanacle
[{ "id": 1, "text": "100-VOLKAN DİLLİOĞLU" }, { "id": 18, "text": "100-BÜLENT HASIRCI" }, { "id": 34, "text": "100-SEMRA TAŞDEMİR" }, { "id": 37, "text": "100-GÜRKAN ÖZTÜRK" }, { "id": 22, "text": "100-HASAN ABLAK" }, { "id": 24, "text": "100-SEVİL AŞKIN" }, { "id": 49, "text": "100-SELMA KABAKÇI" }, { "id": 59, "text": "100-MÜJDAT DÜŞMEZ" }, { "id": 81, "text": "100-HANDAN CANAN AYYILMAZ" }]Tabular

© 2022 - 2024 — McMap. All rights reserved.