Home >Web Front-end >JS Tutorial >How to Efficiently Add Options to a Dropdown Using jQuery?

How to Efficiently Add Options to a Dropdown Using jQuery?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 05:49:09685browse

How to Efficiently Add Options to a Dropdown Using jQuery?

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!

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