Click here to Skip to main content
14,734,763 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>
                                               </select>


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
Posted
Updated 10-Apr-19 7:06am

why not val()[^]
$('#drprojecttype').val("Adhoc")


using vanilla javascript

document.getElementById('drprojecttype').value = "Adhoc"
   
v2
Comments
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
   
cool,
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!
   
Comments
David_ElBro 28-Aug-18 20:49pm
   
Thanks it works so nice
Var YouValue ="100";

$("#ddlID > [value=" + YouValue + "]").attr("selected", "true");
   
Comments
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