select2标签没有名字

时间:2016-02-10 15:27:30

标签: jquery jquery-select2-4 select2

我使用这段代码来应用保存在数据库中的上一页所做选择的标记。

它会创建标签,但不会将文本放入其中,只需放入X即可将其删除。 selected是一系列可能的位置。

["work", "home", "away", "Hong Kong", "Manchester".......]

var selected = this.location
var $element = $("#location").select2();
for (var d = 0; d < selected.length; d++) {
    var item = selected[d];
    var option = new Option(item.text, item.id, true, true)
    $element.append(option);
}

任何帮助都会受到赞赏,因为这里的所有select2问题似乎主要是处理静态数据,或者是为了我当前的知识水平而提升。

根据要求,

这就是所有代码明智的代码。我只想要标签中的文字

目前看起来像http://prntscr.com/a1h2nu 我需要它看起来像http://prntscr.com/a1h33w

这是HTML

  <div class="form-group">
        <label for="location" class="col-lg-3 control-label">Location</label>
        <div class="col-lg-8">
            <select class="form-control" id="location" multiple="multiple" style="width: 100%">
            </select>
            <span class="help-block"></span>
        </div>
    </div>



var item = selected[d];
console.log(item);
var option = new Option(item.text, item.id, true, true)
console.log(option);
$element.append(option);

这是dev工具输出 http://prntscr.com/a1hdf7

2 个答案:

答案 0 :(得分:0)

EDIT 可以找到更新的jsFiddle here。主要问题是你错过了正确的选择器。

为了让Select2考虑您的更改,您需要触发更改,以便重新评估控件。

你可以看到现场小提琴here

$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });

参考Select2文档Programmatic Access

答案 1 :(得分:0)

这是一个简单的修复 从这......

var item = selected[d];
console.log(item);
var option = new Option(item.text, item.id, true, true)
console.log(option);
$element.append(option);

对此...

var item = selected[d];
console.log(item);
var option = new Option(item, item.id, true, true)
console.log(option);
$element.append(option);
相关问题