Click here to Skip to main content
15,397,218 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
if (projecttype == "FTE" || projecttype == "Retainer") {
              //  $('#drprojecttype').val("Dedicated");
              $("#drprojecttype option[value='Dedicated']").attr("selected", "selected");
            //  $("#drprojecttype").val("Dedicated");
          else {
              // $("#drprojecttype").val("Adhoc");
              $('select[name^="drprojecttype"] option:selected').attr("selected", null);
              $("#drprojecttype option[value='Adhoc']").attr("selected", "selected");

Html code:-

<select id="drprojecttype" name="drprojecttype" class="form-control" style="width:50%;">
                                                   <option value="0">--select--</option>
                                                   <option value="Adhoc">Adhoc</option>
                                                   <option value="Dedicated">Dedicated</option>

What I have tried:

I was trying to set selected value to my dropdownlist. I searched on google but didn't found the satisfactory answer. please help
Updated 10-Apr-19 6:06am

why not val()[^]

using vanilla javascript

document.getElementById('drprojecttype').value = "Adhoc"
Member 10549697 7-Mar-17 0:25am
the val() is not working here.
Karthik_Mahalingam 7-Mar-17 0:27am
right click the browser and check the select tag how it is formed.. and post the element here..
Member 10549697 7-Mar-17 0:51am
Hi Karthik. It's working properly. Thank you!
Karthik_Mahalingam 7-Mar-17 0:52am
Member 14125906 29-Jan-19 15:17pm
tell me how bro ....!
Karthik_Mahalingam 29-Jan-19 19:22pm
What to tell
With jQuery, simply by retreiving the DOM node ... $( <selector> ).get(0) and use the native Javascript property .selectedIndex.
Set the index of the option (not the value) !
$( <selector> ).get(0).selectedIndex = <required-index>

When we have the option value, so use the CSS Attribute selector, and .attr()
$( <selector> ).find('option[value="<required-value>"]').attr('selected','selected')

To fetch the index (position of the option in DOM tree) of an option by its value, use:
idx = $( <selector> ).find('option[value="<required-value>"]').index()

Note: the index position start at 0!
David_ElBro 28-Aug-18 20:49pm
Thanks it works so nice
jeproxsikat99 3-May-21 23:17pm
This works so good!
Var YouValue ="100";

$("#ddlID > [value=" + YouValue + "]").attr("selected", "true");
Member 10549697 7-Mar-17 0:21am
It works. Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900