How to Clear a Drop-Down in JQuery

104 1
    • 1). Open a Web browser and go to the jQuery website (jquery.com). Select the latest production version using the check boxes at the top-right of the jQuery homepage. Click on the "Download jQuery" button and save the file into a directory within the local copy of your website. Upload the jQuery file to your Web server using an FTP application.

    • 2). Open a text editor or web design application and create a new HTML page. Add the following line between the HTML "<head>" and "</head>" tags at the top of the page to include the jQuery library.

      <script type="text/javascript" src="/jquery/jquery-1.6.2.min.js">

      Change the path in the script src attribute to match the directory name on your server, and the version of jQuery you downloaded.

    • 3). Add the following code between the HTML "<body>" and "</body>" tags.

      <form name="myForm" method="post" action="">

      <select name="myDropdown">

      <option value="1">1</option>

      <option value="2">2</option>

      </select>

      <input type="button" name="clear-dropdown" value="Clear" />

      </form>

      This adds a HTML form to the page containing a drop-down menu with two example options. The form also contains a button that the user can click to clear the drop-down menu.

    • 4). Add the following code inside the HTML input tag for the button, after the value attribute:

      onclick="$('#myDropdown').empty();"

      This JavaScript runs when the visitor clicks the button, using the buttons onclick event. The first part of the code before the period references the drop-down menu with the id myDropdown, using the jQuery selector system. The jQuery empty function removes all child nodes from the selected element. This removes all the options nested inside the select tag for the drop-down with the id myDropdown, instantly clearing the drop-down menu.

    • 5). Save the page as example.htm and save to the root directory of the website. Upload the page to your Web server using a FTP application, and then open the page in your browser. Initially, the drop-down menu contains the two example options. Click the "Clear" button to clear the drop-down menu.

Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.