Add and Remove Options in Select using jQuery


In this tutorial, you will learn how to remove and add the options in the select box. jQuery is the best way to implements the JavaScript and reduce the time and efforts as well.

Add Options

We can dynamically add the options in the select box using jQuery append() method.

$("#item").append("<option value='item" + i + "'>Item " + i + "</option>");

This example will add an option in select box on button click.
Check the complete example here…

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                var i = 0;
                $("#add").on("click", function () {
                    i++;
                    $("#item").append("<option value='item" + i + "'>Item " + i + "</option>");
                    alert("New item added.");
                });
            });
        </script>
    </head>
    <body>
        <h1>Add and Remove Options in Select using jQuery</h1>              
        <label for="item">Item List:</label>
        <select id="item">
            <option>Select Item</option>           
        </select>
        <button type="button" id="add">Add Item</button>
    </body>
</html>
Output:

Remove Options

To remove an option, you can use the remove() method of jQuery.

This will remove the selected option from the select box.

 $("#country option:selected").remove();

This will remove the option where a condition is applied.

$("#country option[value='russia']").remove();

Check the complete example here…

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#remove").on("click", function () {
                    $("#country option:selected").remove();
                    alert("Selected country removed.");
                });
            });
        </script>
    </head>
    <body>
        <h1>Add and Remove Options in Select using jQuery</h1>
        <label for="country">Country List:</label>
        <select id="country">
            <option value="none">Select Country</option>
            <option value="india">India</option>
            <option value="usa">USA</option>
            <option value="russia">Russia</option>
            <option value="nepal">Nepal</option>
        </select>
        <button type="button" id="remove">Remove Country</button>
    </body>
</html>
Output:

 

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.