Add a single option element to select JQuery

Posted on

This article is written for trying to give a description or an information to add single option HTML element to select HTML element using JQuery. The option element is only a single element. Another article which has the same purpose on adding option element to a select HTML element can be seen in the following article titled ‘Add select option JQuery from Array Variable‘. But the main different is adding an option HTML element to the select HTML element executed by feeding an array variable which is iterated. In this context of article, it is only need one single option element to be inserted to the select HTML element.

A single option HTML element can be inserted into an already declared or existing select HTML element. Below are the steps taken to fulfill the purpose :

1. Define the select HTML element in the web-page file as shown below :

<select id="list_selection">
</select>

2. Set in the tag ‘<script>’ which has already been defined its attribute, ‘type’ has a value of ‘text/javascript’ so that it indicate every lines of code enclosed within the tag is considered as a Javascript snippet code. It will aware the Web Browser to interpret the snippet code as a Javascript code. It is shown in the following snippet code :

<script type="text/javascript">
</script>
  1. Add the script or Javascript line of code which is considered as a script to add a single option HTML element to a select HTML element as shown below :
$('#list_selection').append("<option value="+element_value+">"+element_text+"</option");

Another script which is a different but it has the same purpose is shown below :

$('#list_selection').append(new Option(element_text, element_value));

As shown in the above snippet code, there are two components or attributes which is constructing the option element. The first is element_value and the latter is ext. The element_value variable is one of the important part constructing the o HTML element since it is defining the value¬† is being carried by the element itself. Another part which is also quite important is the label or text part which is in the above snippet code is represented by a variable named ‘element_text’.

Just define the variables along the script above. Just declare it before the script above so the variables already been defined and it can be used properly.

One thought on “Add a single option element to select JQuery

Leave a Reply