Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preselecting value in select2

Texbox is dynamically filled with a remote call using Select2 and how do I set preselected value. Here is the code

<input type="hidden" id="e6">

$("#e6").select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    ajax: {
        url: url,
        dataType: 'jsonp',
        data: function (term, page) {
            return {
                q: term, // search term 
                page_limit: 10, }; 
        }, 
        results: function (data, page) { 
                return {results: data};
        }
    }
});    

I tried this to preselect value 1049

$('#e6').select2('val', '1049');

but this doesn't set the value on the textbox.

Any ideas?

like image 258
Smith Avatar asked Mar 18 '14 14:03

Smith


2 Answers

in 2019 this worked for me

    // Create a DOM Option and pre-select by default~
    var newOption = new Option(data.text, data.id, true, true);
    // Append it to the select
    $('#mySelect2').append(newOption).trigger('change');
like image 133
first day of your life Avatar answered Sep 30 '22 16:09

first day of your life


In case anybody wants to know how to solve this

$("#e6").select2('data', {id: '1049', text: 'MyLabel'});
like image 34
Smith Avatar answered Sep 30 '22 17:09

Smith