How to Remove, Add, and Select the Options of a Select Tag Using jQuery

Neha Imran Feb 02, 2024
  1. Add Options of the <select> Tag
  2. Remove Options of the <select> Tag
  3. Remove, Add, and Select the Option of a Select Box Using jQuery
How to Remove, Add, and Select the Options of a Select Tag Using jQuery

We’ll focus on three distinct features in this article. The first involves adding the option, the second is removing the option, and the third involves performing both actions within the same code.

Today’s article aims to delete all of the existing options of a select tag, then add new options and select them. All of these actions should be performed with the help of jQuery. We’ll go in small steps.

We will first study how to add options, discover several methods for removing options, and finally, learn how to delete, add, and select options in one code snippet.

Add Options of the <select> Tag

We usually add the options of a <select> tag without using JavaScript, but we may sometimes need to add the options in the drop-down menus of our web pages using jQuery or JS. We will discuss some methods which will help us add the options.

Use JavaScript to Add Options

We’ll start by talking about adding the options using JavaScript. We have a lot of flexibility to play with the elements of our web pages thanks to JavaScript’s ease of use.

Check out the requirements for adding the <option> in the code below.

<html>
    <head>
        <script>
            window.onload = function(){
                var length = document.getElementById("drop_down").options.length;
                drop_down.options[length] = new Option ("Text4");
            }

        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

add options - javascript

The length variable will be set to 3 since the <select> tag contains three options. The index can be used to find any tag.

When we talk about the options in the <select> tag, the first option is at index 0. The second is at index 1, and so on.

We can add a new option by determining the entire length of the options array and then creating a new option at the index adjacent to the last one, as shown in the code.

Use the .append() Methodt to Add Options

The following technique we can use to add the options to the existing <select> tag is the .append() method of jQuery. The append() method adds the content to the end of the chosen elements.

We can pass the text as well as HTML elements in the parameter. Check the code and its output below to understand the working of the .append() method.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
               $("#drop_down").append('<option>Text4</option>')
            });
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

add options - append

The append() function adds the option at the end, as seen in the output. You can use the .prepend() function to add the option at the beginning.

You can also add options to the locations other than start or end. To insert the option after any specific option, you can use the after() method, and to add the option before the selected one, you can use the .before() method.

Remove Options of the <select> Tag

We can remove the options of a drop-down list using JavaScript and jQuery. Let’s discuss different approaches to help us remove a <select> tag’s options.

Use the .find() and .remove() Methods to Remove Options of the <select> Tag

The first method we will discuss for removing the options of a select tag is using jQuery’s .find() and .remove() methods.

.find(): This method retrieves the element’s descendent elements. Children, grandchildren, great-grandchildren, and so on are all considered descendants. In contrast to the other tree traversal techniques, the find() function requires the filter parameter.

.remove(): The selected element and its children elements are removed using this jQuery method.

Let’s see the working of these two functions in the code below.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#drop_down').find('option').remove();
            });
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

remove options - find and remove

As was said earlier, the find() method requires the filter parameter, so we gave the option as the filter, making it retrieve all option tags from the select element. Then we invoked the remove method, which removed all the option tags obtained, as seen in the output.

You can also remove only one particular option from a select tag without removing them all. It can be eliminated by simply specifying the option’s index.

For example, if we want to remove the second option, we know it will be at index 1. We can simply type $('#drop down').find('option')[1].remove() to delete it.

Use the .children() and .remove() Methods to Remove Options of the <select> Tag

Another method we can use to remove all the options of a <select> tag is using the .children() and .remove() methods. The .remove() method removes all the selected elements, and the .children() method returns all of the direct children of the selected element.

Observe the code below to understand the working of these methods.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#drop_down').children().remove();
            });
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

remove options - children and remove

Use the .empty() Method to Remove Options of the <select> Tag

If you don’t want to use multiple methods to remove the options, don’t worry; jQuery has got you covered. jQuery has a .empty() method that removes all the child elements of the selected element. This method will not remove the element itself.

For understanding, examine the code and its results.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#drop_down').empty();
            });
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

remove options - empty

The drop-down is still there but with no options, as seen in the output.

Use the .options Method to Remove Options of the <select> Tag

Another helpful method for removing the option is using the .options feature of JavaScript. This is the conventional method for clearing all options.

The .options method returns all the options of a drop-down list. What we have to do is to put options.length equal to zero.

The length method tells us the count of the elements contained in a particular element. If we set it to zero, it indicates that there isn’t any element inside the selected one. Amazing, right?

Have a look at the code for a better understanding.

<html>
    <head>
        <script>
            window.onload = function(){
                document.getElementById("drop_down").options.length=0;
            }
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

remove options - javascript

Remove, Add, and Select the Option of a Select Box Using jQuery

Up till now, we have covered the methods and strategies for utilizing jQuery to add and remove options from a select tag. As we come closer to the article’s primary objective, we will go over combining the operations of adding, removing, and selecting in a single code.

There are numerous ways to achieve this functionality. To help you comprehend, we’ll go over each technique in depth. Let’s begin.

Use the .remove() and .append() Methods to Remove, Add, and Select the Option

We believe you are now quite familiar with the .remove() and .append() jQuery methods. We will use the .remove() to remove all the option tags of the selected element and then .append() to add a new option.

Check the code below to understand.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#drop_down')
                    .find('option')
                    .remove()
                    .end()
                    .append('<option value="4">Text4</option>')
                    .val('4');
            });
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option value="1">Text1</option>
            <option value="2">Text2</option>
            <option value="3">Text3</option>
        </select>
    </body>
</html>

Output:

remove, add, and select the option - remove and append

You might be confused about why there is a .end() method and what it does. The most recent filtering action in the current chain is terminated using the .end() method in jQuery.

When jQuery is used for chaining, the .end() method is helpful.

Last, we applied the .val() method to set the selected element’s value. We used this because we wanted to choose the option we added.

Use the .empty() and .append() Methods to Remove, Add, and Select the Option

Another approach we discussed for removing all the options of a drop-down list is the .empty() method, which will remove all the options, and then we will use .append() to add a new option. Check the code below.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
               $('#drop_down').empty().append('<option selected="selected">Text4</option>');
            });
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

remove, add, and select the option - empty and append

Use JavaScript to Remove, Add, and Select the Option

For our necessary functionality, JavaScript can be used. In the sections above, we went into great detail on adding and removing options using JavaScript.

For a better understanding, look at the code below.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                var mySelect = document.getElementById('drop_down');
                mySelect.options.length = 0;
                mySelect.options[0] = new Option ("Text4");
                mySelect.options[0].selected="true";
            });
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

remove, add, and select the option - javascript

Replace the Content Using the .html() Method

By replacing the entire content of the <select> tag with the new required option, we may remove all the options from a <select> tag, add a new option, and select it using jQuery. For this, we’ll use the .html() method.

The .html() method either sets or returns the specified element’s content. When used to retrieve content, this function returns the content of the first matched element, and when used to set content, this technique overwrites the content of all matched elements.

Let’s see the working of this method.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
             $("#drop_down").html("<option selected=\"selected\">Text4</option>")
            });
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

replace the content - html

The content completely replaces the existing content of the <select> tag we specified in the .html() method, as seen in the output.

Replace the Content Using the .replaceWith() Method

The jQuery .replaceWith() method allows us to replace the selected element with the specified content. Check the code to figure out the method for replacing the content.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $('#drop_down').replaceWith('<select id="drop_down">																						<option selected="selected">Text4</option> 											 					 </select>');
   				});
        </script>
    </head>
    <body>
        <select id="drop_down" style="width:100px">
            <option>Text1</option>
            <option>Text2</option>
            <option>Text3</option>
        </select>
    </body>
</html>

Output:

replace the content - replacewith