add option to select using jquery

How to Add Option to Select Using jQuery

jQuery is a powerful JavaScript library that allows you to manipulate DOM elements easily. It allows you to modify different types of DOM elements such as buttons, links, dropdowns and more, as per your requirement, using very simple lines of code. Sometimes you may need to add option to select dropdown using jQuery. There are several ways to do this. In this article, we will learn how to do this in a couple of ways.


How to Add Option to Select Using jQuery

Let’s say you have the following dropdown.

<select id='mySelect'>
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="peaches">Peaches</option>
</select>

Let’s say you want to add the following option to the above select dropdown.

<option value="orange">Orange</option>

There are several ways to do this. In all cases, we will use append() function for this purpose.

1. Using jQuery Object

In this case, we create an object for option tag and append it to select element.

$('#mySelect')
         .append($("<option></option>")
                    .attr("value", 'orange')
                    .text('Orange')); 

This approach first creates an option element and then sets its value attribute, HTML text and then appends it to mySelect dropdown. This is intuitive but slower since jQuery needs to call multiple functions just to add one option. Nevertheless, it is easy to debug if things go wrong.

2. Using Literal HTML

In this case, we simply use the HTML for option tag in append() function.

$('#mySelect')
         .append('<option value="orange">Orange</option>'); 

This approach is faster but it can become tricky if your option is large with many attributes. In such cases, you will end up with really large HTML strings which can become difficult to manage. This is also difficult to debug since it may contain many quotes inside your string, especially if you are using variables to substitute values. Here is an example to illustrate this point. Just look at the number of quotes in the HTML string used in append() function below.

$('#mySelect')
         .append('<option value="'+value+'">'+text+'</option>'); 

In this article, we have learnt two simple ways to add option to JS dropdown, using jQuery. You can use any of them as per your requirement. If you need to add only a few options that are simple or your options have many attributes, then you can use the first method since it is intuitive and easy to debug, but if you need to add many options then use the second method since it is faster.

Also read:

How to Use JavaScript Variables in jQuery Selectors
How to Select Element with Multiple Classes in jQuery
How to Show Last Queries Executed in PostgreSQL
How to Generate Random Color in JavaScript
How to Read from Stdin in Python

Leave a Reply

Your email address will not be published.