Preselecting value in select2
Asked Answered
O

10

12

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?

Orin answered 18/3, 2014 at 14:8 Comment(0)
O
22

In case anybody wants to know how to solve this

$("#e6").select2('data', {id: '1049', text: 'MyLabel'});
Orin answered 18/3, 2014 at 14:44 Comment(3)
you have a typo - $("#e6")Saccharine
@smith how to pre-select more than 1 value ??Upchurch
@VikashSingh use this: [ {id: '1049', text: 'MyLabel'} , {id: '10', text: 'Mybel'} ]Mcshane
U
6

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
Untuck answered 21/11, 2019 at 13:5 Comment(0)
A
4

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');
Anoxemia answered 30/7, 2019 at 14:17 Comment(0)
O
3

I got it to work with

$("#e6").val("input id of the select2 option here").trigger("change")
Oscillation answered 4/7, 2019 at 5:19 Comment(0)
B
2

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

Brotherhood answered 18/3, 2014 at 14:24 Comment(1)
this doesn't work, initSelection is only called when the hidden input you attach to has a non-empty value attribute.Orin
A
2

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);
Astomatous answered 6/1, 2015 at 17:10 Comment(0)
C
1

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.

Croquette answered 27/3, 2023 at 20:43 Comment(0)
D
0

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>
Disperse answered 13/11, 2019 at 6:30 Comment(0)
N
0

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

Natheless answered 16/1, 2022 at 17:7 Comment(0)
E
0

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

Elver answered 28/3, 2022 at 14:33 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewRostand

© 2022 - 2024 — McMap. All rights reserved.