0

I have looked at multiple questions on SO and on Git hub:

But I still cant seem to figure out why the values is not being set.

I am using a jinja2 template, so Ill give the generated 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>

and the 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");

});

I have also managed to reproduce the result, see example.

Community
  • 1
  • 1
Renier
  • 1,523
  • 4
  • 32
  • 60

1 Answers1

2

The issue occurs because you have set the multiple property to true. In this case to set a value you need to use an array instead of a string.

For example:

$(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"]);
});

A working demo here: http://jsfiddle.net/nww22qoj/19/

Edit: Here is a working jsfiddle using the 4.0.1 version of the plugin http://jsfiddle.net/nww22qoj/20/ (using the full version of the plugin)

Tasos K.
  • 7,979
  • 7
  • 39
  • 63