How to perform operations on select box using jQuery / Drop down jQuery cheat sheet

There are many operations which we have to perform on select boxes (or drop downs) such as selecting an option based on index, selecting an option based on visible text, removing an option etc. using jQuery.

Most of the times, we do not remember the selectors or methods to accomplish the required task and we end up searching the Internet giving away our valuable time. In this post, I have tried to accumulate various operations and their methods which should be helpful to many. Read On !!!

Consider the following drop down of languages as the subject drop down and all our sample code will be using this element.

   <select id="testDropDown">
       <option value="0">Select</option>
       <option value="1">English</option>
       <option value="2">Japanese</option>
       <option value="3">Chinese</option>
       <option value="4">Spanish</option>
       <option value="5">French</option>
   </select>
  1. Select option based on value
    All drop down options have a value attribute. It is this value which should be stored in the database and not the visible text. Hence this value is taken to be short and is identified by the application and not the visible value.
    Now let’s say we have a value 3 and we want the option with this value to be selected. Following is the way to do that.

           A.   // val() method matches the given value with the all the options
                // and selects the one which matches
                $("#testDropDown").val("3")
     
           B.   // find option whose value attribute has the given value
                $("#connectorTransactions option[value=3]")

    Note : Both the above snippets of code will give you the option whose visible text matches with the supplied text. In order to set that option selected, append .prop('selected',true) at the end.

  2. Select option based on visible text
    Select the option whose visible text is the same as the provided value. It can be done as:

          A.   // use the contains operator to find the option which has the given text  
               $("#testDropDown option:contains(Spanish)")
     
          B.   // filter method of jQuery matches the selector with the given value and
               // returns matching options
               $("#testDropDown option").filter(function() {
                    return $(this).text() =='Spanish';
               });


    Note :
    Both the above snippets of code will give you the option whose visible text matches with the supplied text. In order to set that option selected, append .prop('selected',true) at the end.

  3.  Get the value of selected option from a drop down
    Fetch the value attribute of the option which is selected. Do it as below:

          A.   // find selected option using jQuery ":selected" selector and get its value   
               $("#testDropDown option:selected").val()
     
          B.   /* simplest way to get the selected option value */
               $("#testDropDown").val();
  4.  Get the text of selected option from a drop down
    Fetch the visible text of the selected option of dropdown. Do it as below:

          A.   // find selected option using jQuery ":selected" selector and get its text   
               $("#testDropDown option:selected").text()
     
          B.   /* simplest way to get the selected option value */
               $("#testDropDown").val();
  5.  Remove duplicate options from a drop down
    Fetch the visible text of the selected option of dropdown. Do it as below:

               // initialize a map to check duplicates   
               var optionValueMap = {};
               // iterate over drop down options 
    	   $('#testDropDown > option').each(function() {
                   // check if value exists in the array, if yes
                   // then remove the option from drop down
    	       if (optionValueMap[$(this).val()]){
                      // this refers to the the drop down option
    	          $(this).remove();
    	       } else {
                      // add key as the value of option and a boolean true as value.
                      // this will be used in the above if condition
    	          optionValueMap[$(this).val()] = true;
    	       }
    	   });

That brings us to the end of this post.
If you are reading this, means you have read this post till the end and liked it. Post your comment for any clarifications/corrections.

0

Leave a Reply

Mark Your Impression

  Subscribe  
Notify of
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.