mllamazares
mllamazares

Reputation: 8166

How to append text to selected item in select2?

I'm trying to edit the selected value of a select2. So I did this simple code:

http://jsfiddle.net/rcky9/2/

HTML

<select id="sel" style="width: 100%">
    <option value="1">Hello</option>
    <option value="2">Friends</option>
    <option value="3">Stackoverflow</option>
</select>
<br><br>
<button id="addok">Add OK</button>

JS

$(document).ready(function () {

    $("#sel").select2();

    $("#addok").click(function() {
        actual_value = $("#sel").find(':selected').text();

        if (actual_value.indexOf(" OK") > -1){
            return
        }

        newtext = actual_value + " OK";

        // this works.
        $("#sel").find(':selected').text(newtext);

        // this does not works.
        $('#s2id_sel').find('.select2-choosen').text(newtext);
    });
});

As you see, after pressing the button, looks like nothing had changed, but if you open the dropdown, the OK was added successfully at the current item.

The problem appears when I try to modify the actual value located in a div with select2-choosen css class. I can't access it by this way.

Do you have any idea, advice or tip to do this?

Upvotes: 0

Views: 2669

Answers (1)

Adil
Adil

Reputation: 148120

Firing the change() on select will show the appended ok, you need to trigger change() There is no element with id s2id_sel and class .select2-choosen to last statement wont change the text.

Live Demo

$("#sel").find(':selected').text(newtext).change();

Upvotes: 2

Related Questions