Add select option JQuery from Array Variable

Posted on

The main point of this article is how to add an option HTML element inside a select HTML element using JQuery. The content of the option HTML element is provided from an array variable. The steps on doing it is by defining an array variable with several data or values. After finished on defining or declaring the variable, just pass it to be rendered or iterated in for generating options element.

Below is the description of each step :

1. Defining the variable or value in form of an array variable with the following example below :

var db_list = new Array("PostgreSQL","MySQL","Microsoft SQL Server");

The above snippet code is not working, so the associative array variable with the correct one can be declared as follows :

var db_list = {"1":"PostgreSQL","2":MySQL","3":"Microsoft SQL Server");

It is a variable named ‘db_list’. It consists of several values describing names of RDBMS such as PostgreSQL, MySQL and Microsoft SQL Server for an example. This variable will be passed to a function used to generate the option HTML element.
Remember precisely to enclose the above snippet code definition inside the HTML tag of <script type=”text/javascript”></script> to be declared and processed further as a Javascript.

2. Generate the option HTML element by using the following snippet code :

   $.each(db_list, function(key, value) {

There are several things which can be explained from the above snippet code declaration or definition. It is started with removing or emptying elements which can be already exist before from a HTML element identified by an id named ‘list_selection’. Below is the part aiming for that :


3. Based on the above snippet code declared, don’t forget to the define the select HTML element inside the body HTML tag. It is an important part for preparing the container of the option element generated. Below is the snippet code declared for that :

<h1>Switch to List</h1>
<select id="list_selection">

The important part in the above declaration is the following part :


<select id="list_selection">

It is clearly the part for declaring a select HTML element with an id of ‘list_selection’. The id attribute itself is important for informing JQuery to locate the select HTML element so that JQuery itself can successfully insert or add the option HTML element associated which is intended to be generated.

So, add or generate a select option or a dropdown list HTML element using an array variable with the help of JQuery has finished with the following output :

Add select option JQuery from Array Variable
Add select option JQuery from Array Variable

2 thoughts on “Add select option JQuery from Array Variable

Leave a Reply