简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM