Search code examples
jqueryjquery-select2-4jquery-select2

jquery select2 setting input value


I have the following input textbox using select2:

<div class="col-md-6">
    <div class="form-group">
        <label for="QRY_Owner"> Owner ID</label>
        <input id="QRY_Owner" type="text" style="width:100%">
        </input>
    </div>
</div>

which is setupusing select2 like this:

            $("#QRY_Owner").select2({
                placeholder: "Owner ID",
                tags: [],
                tokenSeparators: [",", " ", ";"],
                maximumInputLength: 12,
                selectOnBlur: true,
                dropdownCssClass: "hiddenSelect2DropDown"
            });

Now, I want to set the default values for the text input. I tried the following:

$("#QRY_Owner").select2("val", "test value");

and the following:

$("#QRY_Owner").select2({
    tags:  ["red", "green", "blue"]
});

and the following:

 $("#QRY_Owner").val("close");

But the form does not get updated and the input fields are blank. Also, I do not get any errors in the browser console.

Any thoughts on what am i missing here?

Here is a jsfiddle which shows my problem: https://jsfiddle.net/snehilw/90m8hzpg/


Solution

  • Grabbed from JQuery select2 set default value from an option in list?. Just add:

    .select2('val', ['AL', 'WY'])
    

    jsfiddle