Clear items from DropDownList (or) Select in Java script

Introduction:

In this article i will explain how to clear items from DropDownList (or) Select in Java Script.

Description:

In previous articles i explained How to replace string in Java ScriptHow many ways we can replace the string in Java ScriptHow to work with TextBox in Java ScriptHow to create a HTML Table dynamically in Java Script, and How to Create/Insert rows dynamically to HTML Table and Remove/Delete rows from HTML Table in Java Script. Now i will explain how to clear items from DropDownList (or) Select in Java Script.

Clear items from DropDownList (or) Select in Java Script:

We can clear items from DropDownList (or) select as shown below:

Script:

document.getElementById('ddlRole').options.length = 0;

You can also find the complete example as shown below:

Full Source Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>How to clear items from DropDownList (or) Select in Java Script</title>
    <script type="text/javascript">
        function ClearItems() {
            document.getElementById('ddlRole').options.length = 0;
        }
    </script>
</head>
<body>
    <div>
        <select id="ddlRole" class="form-control">
            <option value="-1">Select</option>
            <option value="1">User</option>
            <option value="2">Admin</option>
            <option value="3">Super Admin</option>
        </select>
        <input type="button" value="Clear" onclick="ClearItems(this)" />
    </div>
</body>
</html>

In the above example, it will clear all the items from DropDownList (or) Select when we click on Clear button.

Output:

Before Clear

 

After Clear