Populating Dropdown Options with jQuery
Question:
How to effortlessly add options to a dropdown using jQuery? Specifically, is this code snippet correct:
$("#mySelect").append('<option value=1>My option</option>');
Answer:
Yes, the provided code is functional. However, there's a more elegant approach to achieve the same result.
Preferred Syntax for Appending Options:
$('#mySelect').append($('<option>', { value: 1, text: 'My option' }));
This syntax allows you to specify both the value and text of the option in a single line.
Looping Through Collection of Items:
If you need to add multiple options from a collection of items:
$.each(items, function (i, item) { $('#mySelect').append($('<option>', { value: item.value, text : item.text })); });
This method iterates over each item in the collection and dynamically creates the necessary options.
The above is the detailed content of How to Efficiently Add Options to a Dropdown Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!