JQuery select2 set default value from an option in list?

前端 未结 10 744
傲寒
傲寒 2020-12-04 13:07

I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.

相关标签:
10条回答
  • 2020-12-04 13:25

    For 4.x version

    $('#select2Id').val(__INDEX__).trigger('change');
    

    to select value with INDEX

    $('#select2Id').val('').trigger('change');
    

    to select nothing (show placeholder if it is)

    0 讨论(0)
  • 2020-12-04 13:29
        $('select').select2("val",null);
    
    0 讨论(0)
  • 2020-12-04 13:31

    Don't know others issue, Only this code worked for me.

    $('select').val('').select2();
    
    0 讨论(0)
  • 2020-12-04 13:34

    If you are using an array data source you can do something like below -

    $(".select").select2({
        data: data_names
    });
    data_names.forEach(function(name) {
        if (name.selected) {
            $(".select").select2('val', name.id);
        }
    });
    

    This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.

    0 讨论(0)
  • 2020-12-04 13:38
    $("#id").select2("val", null); //this will not work..you can try
    

    You should actually do this...intialise and then set the value..well this is also the way it worked for me.

    $("#id").select2().select2("val", null);
    $("#id").select2().select2("val", 'oneofthevaluehere');
    
    0 讨论(0)
  • 2020-12-04 13:38

    Came from the future? Looking for the ajax source default value ?

    // 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
            }
        });
    });
    

    You're welcome.

    Reference: https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2

    0 讨论(0)
提交回复
热议问题