Select2 set selected value in HTML
Asked Answered
P

2

10

Is there a way I can set selected id/text in select2 in HTML just like is being displayed and selected?

I am using jquery select2 version 4.0.0

this is the code:

$("#users").select2({
    placeholder: "select user...",
    escapeMarkup: function (markup) { return markup; },
    ajax: {
        url: "users.json",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (response, page) {
            return {
                results: response.data
            };
        },
        cache: true
    },
    templateResult: function(item){
        if (item.loading) {
            return item.text;
        }
        return item.username + " <small><i>(" + item.role  + ")</i></small> "; // display data in html
    },
    templateSelection: function(item){
        if (item.username){
            return item.username + " <small><i>(" + item.role  + ")</i></small> ";  // select row in html
        }
        return item.text; // for placeholder
    }
});

To set selected value I do:

// bring data for to set selected value, data contains fields data
var selected_user_id = data.id,

// this is the content that I need to use as it is HTML content
selected_user_text_html = data.username + " <small><i>(" + data.role  + ")</i></small> ",

// this is the one that I am using and is not html because there is no way to put html inside a option select item
selected_user_text_regular = data.username + " (" + data.role  + ") ";

// set selected value
$("#users").append("<option value='"+selected_user_id+"' selected='selected'>"+selected_user_text_regular+"</option>");

// trigger update
$("#users").trigger("change");

Is there a way I can set the selected text in HTML instead of plain text?

Paramnesia answered 8/10, 2015 at 23:39 Comment(1)
probably, I am finding it really hard to work out what you are trying to do. Where is the "To set selected value I do:" code sit. you should probably include the html.Monney
Y
5

Yes, You can. Select2 has a two helpful options "templateSelection" and "templateResult" Both are functions and you may create any html wrapper you wish. Just pass options to select2() method with something like this..

var data = [{id: 100, text: "AAAAAA"}, {id: 200, text: "BBBB"}]

var formatState = function(result) {return $("<b>"+result.text+"</b>")}
var formatSelection = function(selection){return $("<b>"+selection.text+"</b>") }

$(".js-example-basic-single").select2({ data:data,templateResult: formatState, templateSelection: formatSelection
    }).val(100).change();

And you should see the the option with id:100 is selected.

I hope I helped you;

Yoshikoyoshio answered 9/10, 2015 at 0:59 Comment(4)
With local data works fine but there is no way to do that with an Ajax call.Paramnesia
Oh. I see the problem. You should return jQuery object return $('<span>' + item.username + " <small><i>(" + item.role + ")</i></small> "); return $('<span>' + item.username + " <small><i>(" + item.role + ")</i></small></span> ");Yoshikoyoshio
In your callbacks you return plain text and get it in options, just wrap it with jQueryYoshikoyoshio
If you see in the code I am already using template parsers for the result and the selection, the problem is that I cannot add HTML inside a select option like I mentioned.Paramnesia
M
2

if i understand you correctly,

According to the api https://select2.github.io/examples.html , you can set the selected by putting it in the html markup and then calling the javascript

var data = [
     { id: 0, text: 'enhancement' },
     { id: 1, text: 'bug' },
     { id: 2, text: 'duplicate' },
     { id: 3, text: 'invalid' },
     { id: 4, text: 'wontfix' }
 ]

$(".example").select2({
  data: data
})

<select class="example">
    <option value="3" selected="selected">invalid</option>
</select>

Update

Assuming the ajax is called on declaration

would you not be able to append the option when the ajax returns.

ajax: {
 ...
    processResults: function (response, page) {

           //something like
           $.each( response.data, function( i, obj ) {
                if(obj.selected)
                {
                    var elem = $('#users')
                    elem.append($('<option>', { 
                        value: obj.value,
                        text : obj.text,
                        selected : "selected"
                    }));
                }
           })


        return {
            results: response.data
        };
    },
    cache: true
},

Also update

consider the following for replace your other code or giving you ideas

<style>
   .optionrole{
        font-size: small;
        font-style: italic
   }
</style>

var sUserId = data.id,
var sUserText = data.username 
                        + "<span class="optionrole"> (" 
                        + data.role  
                        + ")</span> ";

// set selected value
var elem = $('#users')
elem.append($('<option>', { 
    value: sUserId,
    text : sUserText,
    selected : "selected"
}));

// trigger update
elem.trigger("change");
Monney answered 14/10, 2015 at 19:10 Comment(2)
On the last example you are doing it Ok but do not forget that html code is not allowed inside any option select. That is why I am having the problem to display HTML code inside because I need to do this programatically and not even the parser for selected value (templateSelection) do not allow me to do so.Paramnesia
@IvanJuarez seems you are correct about standards wise html code should not be in a select, had to google that. Back on point.. getting the selected option selected from an ajax return. sorry I couldn't follow your comment as to whether what i suggested worked or not.Monney

© 2022 - 2024 — McMap. All rights reserved.