Friday, February 14, 2014

How To Dynamically Set Select Option Selected Using Jquery?

I have a select field with some options in it and want to select a specific option of a select tag dynamically:
The select List as follows:
<select id="my_val">
      <option value="1">Red</option>
      <option value="2">Green</option>
      <option value="3">Blue</option>

You can solve the above problem using following small piece of jquery function.
 $(document).on('change', '#my_val', function(e) { 
     var option_val = $("#my_val").val(); //store the dynamic value of select option
      $( "#my_val" ).find( 'option[value="' + option_val + '"]' ).prop( "selected", true ); //Set select option 'Selected'
There may be many other possible solutions. Above one worked best for me.

1 comment: