Friday, October 19, 2012

Asp.net jQuery clear dropdown items


In this post, we will see on how to clear the options which exist in a Dropdown list

To clear the existing items from a dropdown we can use the empty() function as follows.  $('yourDropDown').empty();

Here is a full example


Create a new Asp.net page, copy the entire code below, change reference of the jQuery file src="JavaScript/jquery-1.7.2.js" to point to your local directory. Build and run the application, click on the Clear buttons and notice that the Options in the drpCountry dropdown have been cleared off.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>DropDownList</title>
    <script type="text/javascript"
src="JavaScript/jquery-1.7.2.js"></script>
    <script type="text/javascript"
language="javascript">
    $(document).ready(function() {
        $('#cmdClear).click(function(event)
        {
            event.preventDefault();
      $('#drpCountry').empty();
  });
    </script>
</head>
<body>
    <form id="fromDropDownList" runat="server">
    <div>
        Country:
        <asp:DropDownList ID="drpCountry" runat="server">
            <asp:ListItem Value="USA">United States</asp:ListItem>
            <asp:ListItem Value="UK">United Kingdom</asp:ListItem>
        </asp:DropDownList><br /><br />       
        <asp:Button ID="cmdClear"
runat="server"
Text="Clear" />
    </div>
    </form>
</body>
</html>

Search Flipkart Products:
Flipkart.com

No comments: