Tag Archives: dropdown

JavaScript || How To Add & Populate A Dropdown List With An Array Using Vanilla JavaScript

The following is a module with functions which demonstrates how to add and populate a dropdown select list with an array of items using vanilla JavaScript.

The function demonstrated on this page allows to add items from an array into a dropdown list, as well as adding option groups and custom data attributes.


1. Basic Usage

The example below demonstrates the use of ‘Utils.bindDropdown‘ to bind the data in a simple array to a dropdown list.

Sample:


2. Additional Options

The example below demonstrates the use of ‘Utils.bindDropdown‘ to bind the data in an options initialization array to a dropdown list.

In this example, the text and values are specified, as well as custom option groups, the selected option value, and custom data attributes.

You can add any properties you wish to the object, and it will be added to the dropdown list option!

Note: Option groups are not required using this notation, as indicated by the ‘Ungrouped Items’.

Sample:


3. Utils Namespace

The following is the Utils.js Namespace. Include this in your project to start using!


4. More Examples

Below are more examples demonstrating the use of ‘Utils.js‘. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.