How to use jQuery to add new options to the select option box: 1. Add the options tag to the select element; 2. Use the [Option()] method to create a new option; 3. Create using value and text Create a new option element.
The operating environment of this tutorial: Windows 7 system, jquery version 3.3.1. This method is suitable for all brands of computers.
Related recommendations: "jQuery Video Tutorial"
How to use jQuery to add new options to the select option box:
Method 1: Add the options tag to the select element
First use the jquery selector to select the select element, and then use the append() method to add the options tag element. The append() method inserts the specified content into the last subcollection of the jQuery collection. This way the options element is added to the select element.
Syntax:
$('#selectBox').append(`${optionText}`)
Example:
如何使用jQuery向select元素中添加options? 使用jQuery向select元素中添加options
从给定选项中选择一个:
单击下面的按钮,向选择框添加一个选项。
Rendering:
Method 2: Use Option () method creates new options
#Option()
method is used to create new option elements. This method will create a new option using text and the value of the option as arguments. Then use the append() method to add this option element to the selection box.
Syntax:
$('#selectBox').append(new Option(optionText, optionValue))
Example:
如何使用jQuery向select元素中添加options? 使用jQuery向select元素中添加options
从给定选项中选择一个:
单击下面的按钮,向选择框添加一个选项。
Rendering:
Method 3: Using values and text creation creates a new option element
Creates a newjQuery DOM
element using the option tag. The value of the option tag is set using theval()
method, and the text of the option tag is set using the text() method. Then use the append() method to add the created option element to the selection box.
Grammar:
$('#selectBox').append($('
Example:
如何使用jQuery向select元素中添加options? 使用jQuery向select元素中添加options
从给定选项中选择一个:
单击下面的按钮,向选择框添加一个选项。
Rendering:
For more programming-related knowledge, please visit :Programming learning! !
The above is the detailed content of How to add new option to select option box using jQuery. For more information, please follow other related articles on the PHP Chinese website!