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
Release: 2024-11-28 05:49:09
Original
607 people have browsed it

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>');
Copy after login

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'
}));
Copy after login

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
    }));
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template