How do I Set the Selected Value in a jQuery Select2 Dropdown?
Patricia Arquette
Release: 2024-10-27 09:20:03
Original
416 people have browsed it
How to Set Selected Value of jQuery Select2?
Select2 is a powerful jQuery plugin for creating searchable, taggable, and multi-value select boxes. This guide outlines three methods for setting a specific value as selected within a Select2 instance, depending on the version being used (prior to v4 or v4 and above).
Select2 < v4
Create an empty input field: Add an element with the type attribute set to "hidden" and an id attribute that corresponds to the Select2 instance.
Initialize Select2: Create a Select2 instance using the select2() method, passing in the desired options for the instance.
Set the selected value: Use the select2('data', { id: "", text: "" }) method to set the selected value. Specify the id of the item to be selected and any associated text.
Select2 v4 or Above
For HTML Select:
Append the selected option: Add an
Trigger a change event: Use trigger('change') to update the Select2 instance with the new value.
For Non-HTML Select (JQuery):
Create a new option: Use the jQuery $('
Append and trigger change: Append the new option to the Select2 instance using append() and trigger a change event using trigger('change').
For Setting a Simple Value:
Use val(value).trigger('change') to set a simple value without creating a new option.
This code sets the option with the ID "5" and text "Option 5" as selected within the instance of Select2 with the ID "mySelect2."
The above is the detailed content of How do I Set the Selected Value in a jQuery Select2 Dropdown?. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn