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>
</select>

You can solve the above problem using following small piece of jquery function.
 $(document).on('change', '#my_val', function(e) { 
 
     e.preventDefault();
     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.

Comments

Post a Comment

Popular Posts