简体   繁体   English

如何将文本附加到select2中的选定项目?

[英]How to append text to selected item in select2?

I'm trying to edit the selected value of a select2. 我正在尝试编辑select2的选定值。 So I did this simple code: 所以我做了这个简单的代码:

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

HTML 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 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. 如您所见,按下按钮后,看起来没有任何变化,但是如果您打开下拉列表,则在当前项目中成功添加了OK

The problem appears when I try to modify the actual value located in a div with select2-choosen css class. 当我尝试使用select2-choosen css类修改div中的实际值时,会出现问题。 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. 在select上触发change()将显示附加的ok,你需要触发change()没有id为s2id_sel元素和class .select2-choosen to last statement不会改变文本。

Live Demo 现场演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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