HTML Select/Combo/DropDown tips and tricks

<select id="combo">
   <option value="1">One</option>
   <option value="2">Two</option>
</select>
<script>
   $(function () {
      var $Combo= $('#combo'); // assign to a variable

     //Get selected text 
         var selectedText = $('#combo>option:selected').html();
         //or,
         var selectedText = $('#combo option:selected').html(); 

      //Get selected value 
          var selectedVal = $('#combo>option:selected').attr('value');
          //or,    
          var selectedVal = $('#combo option:selected').attr('value');
      
         var selectedVal = $('#combo>option:selected').val();
         var selectedVal = $('#combo option:selected').val();

         var selectedVal = $($Combo, 'option:selected').attr('value');
         var selectedVal = $($Combo, 'option:selected').val();

      //Handle change event
      $regionCombo.change(function () {
                 //code to further...
             });
      });

      
     //Manipulate Selected Index (It cant be done with jquery)
     var $Combo = document.getElementById('combo');
     var selectedIndex = $Combo.selectedIndex; //getting selected index
     $Combo.selectedIndex = 2; //setting selected index

</script>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s