How do I change selected value of select2 dropdown

2019-01-05 08:52发布

I'm using Oleg's select2 demo, but I am wondering whether it would be possible to change the currently selected value in the dropdown menu.

For example, if the four values loaded were: "Any", "Fruit", "Vegetable", "Meat" and the dropdown list defaulted to "Any", how would I be able to change that to "Fruit" in the JqGrid event loadComplete?

Is this possible?

14条回答
贪生不怕死
2楼-- · 2019-01-05 09:02

if you have ajax data source please refer this for bugs free

https://select2.org/programmatic-control/add-select-clear-items

// Set up the Select2 control

$('#mySelect2').select2({
    ajax: {
        url: '/api/students'
    }
});

// Fetch the preselected item, and add to the control

var studentSelect = $('#mySelect2');
$.ajax({
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true);
    studentSelect.append(option).trigger('change');

    // manually trigger the `select2:select` event
    studentSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-05 09:05

If you want to add new value='newValue' and text='newLabel', you should add this code:

  1. Add new Option to <select>:

    var opt = "<option value='newValue' selected ='selected'>" + newLabel+ " </option>";
    $(selLocationID).html(opt);
    
  2. Trigger <select> change to selected value:

    $(selLocationID).val('newValue').trigger("change");
    
查看更多
混吃等死
4楼-- · 2019-01-05 09:07

Just wanted to add a second answer. If you have already rendered the select as a select2, you will need to have that reflected in your selector as follows:

$("#s2id_originalSelectId").select2("val", "value to select");
查看更多
姐就是有狂的资本
5楼-- · 2019-01-05 09:08

if you want to select a single value then use $('#select').val(1).change()

if you want to select multiple values then set value in array so you can use this code $('#select').val([1,2,3]).change()

查看更多
Emotional °昔
6楼-- · 2019-01-05 09:09

My Expected code :

$('#my-select').val('').change();

working perfectly thank to @PanPipes for the usefull one.

查看更多
Animai°情兽
7楼-- · 2019-01-05 09:10

Having some troubles with setting a String option selected in a select2:

With the option: "option string1 /option" used:

$('#select').val("string1").change(); 

BUT with an option with a value: option value "E" string1 /option :

$('#select').val("E").change(); // you must enter the Value instead of the string

Hopes this help someone struggling with the same issue.

查看更多
登录 后发表回答