简体   繁体   中英

Preselected value for select2 tag selectBox

How would you go about having tags already being preselected in their selectbox at the time the page loads? Here's my code so far:

HTML:

<select class="selectBox operatingSystems" multiple="multiple">
    <option>Windows</option>
    <option>OSX</option>
    <option>Linux</option>
</select>

JS:

$(".operatingSystems").select2({tags: true, tokenSeparators: [',', ' ']});

I'm basically trying to get it to look something like it does on the select2 documentation page where they have "orange" and "purple" preselected. From: https://select2.github.io/examples.html#data-ajax 预选标签

You can select an existing option by setting the selected property.

<select class="selectBox operatingSystems" multiple="multiple">
    <option>Windows</option>
    <option selected="selected">OSX</option>
    <option>Linux</option>
</select>

Would pre-select the OSX option in the select box. This isn't specific to Select2, it's how you set a pre-selected option in general for select boxes (both single and multiple select).

You can do this using vanilla JavaScript by setting the selected property on the element.

theOption.selected = true;

Or using jQuery's .val method for setting the value.

$("select").val(["OSX"])

In order for Select2 and other plugins to pick up the change in value, you may need to trigger the change event.

$("select").trigger("change")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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