Smith
Smith

Reputation: 1469

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?

Upvotes: 12

Views: 34521

Answers (10)

El Gucs
El Gucs

Reputation: 967

I know this is an old question, but I had troubles with it too.

Since the select2 is filled when user inputs some text via AJAX, it starts empty. So the previous answers of the type .val('') don't apply. For example:

$('#e6').val('1'); // Select the option with a value of '1'
$('#e6').trigger('change'); // Notify any JS components that the value changed

this won't work since there is no .val to select from.

Then you need to preload some data to the select2. The selected answer which tries to preload the data did not work for me:

$("#e6").select2('data', {id: '1049', text: 'MyLabel'});

(I guess the code and behavior of the plugin has changed since the answer was made and accepted)


Then you solve this in 2 ways:

  1. You can force it to be preloaded by the AJAX using the code in the documentation.

  2. You can preload data and select it with JS. In my case I needed this select2 prefilled with preselected elements while maintaining the AJAX search.

I used the following:

select2 = $('#e6'); 
var option = new Option('MyLabel', 1049, true, true); //The true vars are for preselecting
select2.append(option); //You can repeat this and the previous line for multiselect
select2.trigger('change'); //Call change event so the control updates

The same in fewer lines:

var option = new Option('MyLabel', 1049, true, true); //The true vars are for preselecting. 1049 is the id.
$('#e6').append(option).trigger('change'); //Append option and call change event 

Hope this helps someone.

Upvotes: 1

Badmous
Badmous

Reputation: 135

in my case, my selected values were saved with comma seperated in my database so i used this approach and it worked for me

        var ele = document.getElementById('farmProduce');
        let val =ele.getAttribute('value')
        for(i=0; i < len; i++){ 
            ele.innerHTML = ele.innerHTML + '<option value="' + farm_produce[i].name + '"' + (val.includes(farm_produce[i].name) ? 'selected="'+true+'"' : null)+'>' + farm_produce[i].name + '</option>';
        }

so essentially, just setting the selected attribute to true and false for each option did the tricks for me

Upvotes: 0

Mehmet Kaplan
Mehmet Kaplan

Reputation: 1

According to documentation, you can do it like this for multiple preselection:

$('#mySelect2').val(['1', '2']); 
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

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

Upvotes: 0

Alice
Alice

Reputation: 61

The solution that worked for me (and that is decribed in the documentation) was:

$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed

Upvotes: 6

This worked for me

<script>
  $(function() {
    if (window.formPrefill) {
      // setTimeout to force script to run when all the stack on doc.ready is complete.
      setTimeout(() => $(".js-select2-companies").select2('data', window.formPrefill), 10);
    }
  })
</script>

Upvotes: 0

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');

Upvotes: 4

Auggysg
Auggysg

Reputation: 41

I got it to work with

$("#e6").val("input id of the select2 option here").trigger("change")

Upvotes: 3

zarget
zarget

Reputation: 21

for multiple selection...

var li = $("#e6");
li.select2({
    placeholder: "Placeholder"
});

var unselected = li.find('option:not(:selected)');
var selected = [];
for (var i = 0; i < unselected.length; i++) {
    selected[i] = { id: unselected[i].value, text: unselected[i].text };
}
li.select2('data', selected);

Upvotes: 2

Smith
Smith

Reputation: 1469

In case anybody wants to know how to solve this

$("#e6").select2('data', {id: '1049', text: 'MyLabel'});

Upvotes: 22

VishwaKumar
VishwaKumar

Reputation: 3433

You can use initSelection method

initSelection: function(element, callback) {
callback({id: 1, text: 'default selection with id 1' });
},

Check this link and loading remote data section here

Upvotes: 2

Related Questions