【问题标题】:Set "val" not working(pre selecting)设置“val”不起作用(预选)
【发布时间】:2014-08-20 09:36:46
【问题描述】:

我查看了关于 SO 和 Git 中心的多个问题:

但我似乎仍然无法弄清楚为什么没有设置这些值。

我使用的是jinja2模板,所以我给出生成的html/js:

<div class="form-group">
    <label class="control-label col-sm-4" for="message_type">Meassage Type</label>
    <div class="col-sm-5">
        <input type="hidden" name="message_type" id="message_type" readonly />
    </div>
</div>

和js:

$(function () {
    $("#message_type").select2({
        placeholder: "Email/SMS/PIMS Modal",
        multiple: true,
        width: "300px",
        tokenSeparators: [',', ' '],
        data: [{
            id: "email",
            text: "Email"
        }, {
            id: "pims modal",
            text: "PIMS Modal"
        }, {
            id: "sms",
            text: "SMS"
        }, ],
    });

    $("#message_type").select2("val", "pims modal");

});

我还设法重现了结果,请参阅example

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    出现此问题是因为您已将 multiple 属性设置为 true。在这种情况下,要设置一个值,您需要使用数组而不是字符串。

    例如:

    $(function () {
        $("#message_type").select2({
            placeholder: "Email/SMS/PIMS Modal",
            multiple: true,
            width: "300px",
            tokenSeparators: [',', ' '],
            data: [{
                id: "email",
                text: "Email"
            }, {
                id: "pims modal",
                text: "PIMS Modal"
            }, {
                id: "sms",
                text: "SMS"
            }, ],
        });
    
        $("#message_type").select2("val", ["email"]);
    });
    

    这里有一个工作演示:http://jsfiddle.net/nww22qoj/19/

    编辑:这是一个使用 4.0.1 版插件 http://jsfiddle.net/nww22qoj/20/ 的工作 jsfiddle(使用插件的完整版

    【讨论】:

    猜你喜欢
    • 2012-06-29
    • 2021-01-29
    • 2019-03-10
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多