Home >Web Front-end >JS Tutorial >How Can I Add Options to a `` Element Using jQuery?
Adding Options to a
jQuery offers various methods to effortlessly add options to a dropdown.
Using .append() with HTML String:
While the code you provided can indeed add an option, it requires escaping HTML characters. To simplify this process:
$("#mySelect").append('<option value="1">My option</option>');
Using .append() with jQuery Object:
For greater control and readability, you can create jQuery objects to define the option:
$('#mySelect').append($('<option>', { value: 1, text: 'My option' }));
Bulk Addition from Data Collection:
If you have a collection of items to append as options:
$.each(items, function (i, item) { $('#mySelect').append($('<option>', { value: item.value, text : item.text })); });
The above is the detailed content of How Can I Add Options to a `` Element Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!