Home  >  Article  >  Backend Development  >  How do I Set the Selected Value in a jQuery Select2 Dropdown?

How do I Set the Selected Value in a jQuery Select2 Dropdown?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 09:20:03261browse

How do I Set the Selected Value in a jQuery Select2 Dropdown?

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

  1. 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.
  2. Initialize Select2: Create a Select2 instance using the select2() method, passing in the desired options for the instance.
  3. 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.
  4. Select2 v4 or Above

    For HTML Select:

    1. Append the selected option: Add an
    2. Trigger a change event: Use trigger('change') to update the Select2 instance with the new value.

    For Non-HTML Select (JQuery):

    1. Create a new option: Use the jQuery $('
    2. 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.

    Example:

    <code class="javascript">$('#mySelect2').select2('data', { id: '5', text: 'Option 5' });</code>

    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!

Statement:
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