How can I set the value of a DropDownList using jQuery?

JqueryDrop Down-Menu

Jquery Problem Overview


As the question says, how do I set the value of a DropDownList control using jQuery?

Jquery Solutions


Solution 1 - Jquery

$("#mydropdownlist").val("thevalue");

just make sure the value in the options tags matches the value in the val method.

Solution 2 - Jquery

As suggested by @Nick Berardi, if your changed value is not reflected on the UI front end, try:

$("#mydropdownlist").val("thevalue").change();

Solution 3 - Jquery

If you working with index you can set the selected index directly with .attr():

$("#mydropdownlist").attr('selectedIndex', 0);

This will set it to the first value in the droplist.

Edit: The way I did it above used to work. But it seems like it doesn't any longer.

But as Han so pleasantly points out in the comments, the correct way to do it is:

$("#mydropdownlist").get(0).selectedIndex = index_here;

Solution 4 - Jquery

Try this very simple approach:

/*make sure that value is included in the options value of the dropdownlist 
e.g. 
(<select><option value='CA'>California</option><option value='AK'>Alaska</option>      </select>)
*/

$('#mycontrolId').val(myvalue).attr("selected", "selected");

Solution 5 - Jquery

If your dropdown is Asp.Net drop down then below code will work fine,

 $("#<%=DropDownName.ClientID%>")[0].selectedIndex=0;

But if your DropDown is HTML drop down then this code will work.

 $("#DropDownName")[0].selectedIndex=0;

Solution 6 - Jquery

Best answer for the question:

$("#comboboxid").val(yourvalue).trigger("chosen:updated");

e.g:

$("#CityID").val(20).trigger("chosen:updated");

or

$("#CityID").val("chicago").trigger("chosen:updated");

Solution 7 - Jquery

There are many ways to do it. here are some of them:

$("._statusDDL").val('2');

OR

$('select').prop('selectedIndex', 3);

Solution 8 - Jquery

set value and update dropdown list event

$("#id").val("1234").change();

Solution 9 - Jquery

If you just need to set the value of a dropdown then the best way is

$("#ID").val("2");

If You have to trigger any script after updating the dropdown value like If you set any onChange event on the dropdown and you want to run this after update the dropdown than You need to use like this

$("#ID").val("2").change();

Solution 10 - Jquery

Just make sure the value in the options tags matches the value in the val method.

$("#mydropdownlist").val("thevalue");

If you have some onchange or any other functionalities with drop down you can use below code. It can trigger your onchange or some other functionalities.

$("#mydropdownlist").val("thevalue").change();

More Informations: https://slaford.com/html/how-can-i-set-the-value-of-a-dropdown-list-using-jquery/

Solution 11 - Jquery

I think this may help:

    $.getJSON('<%= Url.Action("GetDepartment") %>', 
              { coDepartment: paramDepartment },
              function(data) {
                    $(".autoCompleteDepartment").empty();
                    $(".autoCompleteDepartment").append($("<option />").val(-1));
                    $.each(data, function() {
                        $(".autoCompleteDepartment").append($("<option />").val(this.CodDepartment).text(this.DepartmentName));
                    });
                    $(".autoCompleteDepartment").val(-1);                                       
              }  
             );

If you do this way, you add an element with no text. So, when you click de combo, it doesn't apear, but the value -1 you added a later select with $(".autoCompleteDepartment").val(-1); let you control if the combo has a valid value.

Hope it helps anybody.

Sorry for my english.

Solution 12 - Jquery

In case when you load all <options ....></options> by Ajax call
Follow these step to do this.

1). Create a separate method for set value of drop-down
For Ex:

function set_ip_base_country(countryCode)
    $('#country').val(countryCode)
} 

2). Call this method when ajax call success all html append task complete

For Ex:

success: function (doc) {
  .....
  .....
  $("#country").append('<option style="color:black;" value="' + key + '">'  +   value + '</option>')
  set_ip_base_country(ip_base_country)
}

Solution 13 - Jquery

Here is a function made to quickly set the selected option:

function SetSelected(elem, val){
		$('#'+elem+' option').each(function(i,d){
		//	console.log('searching match for '+ elem + '  ' + d.value + ' equal to '+ val);
			if($.trim(d.value).toLowerCase() == $.trim(val).toLowerCase()){
		//		console.log('found match for '+ elem + '  ' + d.value);
				$('#'+elem).prop('selectedIndex', i);
			}
		});
	}

Call this function with argument element id and selected value; like this:

SetSelected('selectID','some option');

It is useful when there are lot of select options to be set.

Solution 14 - Jquery

Set drop-down selected value and update changes

$("#PR2DistrictId option[value='@Model.PR2DistrictId']").attr("selected", true).trigger("chosen:updated")

Here we first set value from Model and than updated it on chosen

Solution 15 - Jquery

//Html Format of the dropdown list.

<select id="MyDropDownList">
<option value=test1 selected>test1</option>
<option value=test2>test2</option>
<option value=test3>test3</option>
<option value=test4>test4</option>

// If you want to change the selected Item to test2 using javascript. Try this one. // set the next option u want to select

var NewOprionValue = "Test2"

        var RemoveSelected = $("#MyDropDownList")[0].innerHTML.replace('selected', '');
        var ChangeSelected = RemoveSelected.replace(NewOption, NewOption + 'selected>');
        $('#MyDropDownList').html(ChangeSelected);

Solution 16 - Jquery

Using the highlighted/checked answer above worked for me... here's a little insight. I cheated a little on getting the URL, but basically I'm defining the URL in the Javascript, and then setting it via the jquery answer from above:

<select id="select" onChange="window.location.href=this.value">
    <option value="">Select a task </option>
    <option value="http://127.0.0.1:5000/choose_form/1">Task 1</option>
    <option value="http://127.0.0.1:5000/choose_form/2">Task 2</option>
    <option value="http://127.0.0.1:5000/choose_form/3">Task 3</option>
    <option value="http://127.0.0.1:5000/choose_form/4">Task 4</option>
    <option value="http://127.0.0.1:5000/choose_form/5">Task 5</option>
    <option value="http://127.0.0.1:5000/choose_form/6">Task 6</option>
    <option value="http://127.0.0.1:5000/choose_form/7">Task 7</option>
    <option value="http://127.0.0.1:5000/choose_form/8">Task 8</option>
</select>
<script>
    var pathArray = window.location.pathname.split( '/' );
    var selectedItem = "http://127.0.0.1:5000/" + pathArray[1] + "/" + pathArray[2];
    var trimmedItem = selectedItem.trim();
    $("#select").val(trimmedItem);
</script>

Solution 17 - Jquery

For people using Bootstrap, use $(#elementId').selectpicker('val','elementValue') instead of $('#elementId').val('elementValue'), as the latter does not update the value in the UI.

Note: Even .change() function works, as suggested above in some answers, but it triggers the $('#elementId').change(function(){ //do something }) function.

Just posting this out there for people referencing this thread in the future.

Solution 18 - Jquery

//customerDB is an Array  
for(i of customerDB){   

      //create option and add to drop down list 
      var set = `<option value=${i.id}>${i.id}</option>`;
      $('#dropDown').append(set);

}  


// print dropdown values on console
$('#dropDown').click(function(){
      console.log($(this).val())
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfleshView Question on Stackoverflow
Solution 1 - JqueryNick BerardiView Answer on Stackoverflow
Solution 2 - JqueryIRSHADView Answer on Stackoverflow
Solution 3 - JquerymattssonView Answer on Stackoverflow
Solution 4 - JqueryClydeView Answer on Stackoverflow
Solution 5 - Jquerysalah9View Answer on Stackoverflow
Solution 6 - JqueryAsif RamzanView Answer on Stackoverflow
Solution 7 - JqueryDilip Kumar YadavView Answer on Stackoverflow
Solution 8 - JqueryJignesh JoisarView Answer on Stackoverflow
Solution 9 - JqueryMannu saraswatView Answer on Stackoverflow
Solution 10 - JqueryManoj NioView Answer on Stackoverflow
Solution 11 - JqueryJapineJView Answer on Stackoverflow
Solution 12 - JqueryGrvTyagiView Answer on Stackoverflow
Solution 13 - Jqueryvishwakarma09View Answer on Stackoverflow
Solution 14 - JqueryDeepak TambeView Answer on Stackoverflow
Solution 15 - JquerySikhaView Answer on Stackoverflow
Solution 16 - Jqueryuser9915877View Answer on Stackoverflow
Solution 17 - JqueryTejas JoshiView Answer on Stackoverflow
Solution 18 - JqueryAbeetha HeshanView Answer on Stackoverflow