381

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

y0mbo
  • 4,582
  • 6
  • 41
  • 45
flesh
  • 23,725
  • 24
  • 80
  • 97

18 Answers18

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

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

Nick Berardi
  • 54,393
  • 15
  • 113
  • 135
  • I have a range validator against a drop down list and I am setting the value of the drop down list as you have described above, yet the range validator keeps failing telling me to select a value (when the value selected is within range). Please see my question http://stackoverflow.com/questions/3165033/rangevalidator-not-working-when-selecting-dropdownlist-value-using-jquery – James Jul 07 '10 at 13:14
  • 27
    This doesn't fire the "change" event. – AGamePlayer Jun 29 '13 at 03:31
  • 5
    Wanted to reiterate - make sure you have the "value" attribute set, or this method will not work. (I was helping someone who showed me this and was wondering why it wasn't selecting via the text in the dropdown list.) Wanted to make sure that was clear. – JasCav Sep 26 '13 at 14:56
  • 2
    +1 Had to call `$("#mycontrolId").selectmenu('refresh');` to reflect changes – VladL Nov 15 '13 at 12:49
  • detailed information at this link https://www.htmlgoodies.com/beyond/javascript/convert-a-list-into-a-select-dropdown-using-jquery.html – Niamath Feb 06 '18 at 20:11
74

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

$("#mydropdownlist").val("thevalue").change();
robnick
  • 1,720
  • 17
  • 27
IRSHAD
  • 1,582
  • 11
  • 16
  • 1
    thanks a lot, just one line, neat and helpful to also raise the change() event of a SelectBox using jQuery and Laravel Forms. – WhySoSerious Feb 01 '16 at 15:36
  • This is the only answer where the change actually showed in the dropdown. `selectmenu` is undefined in my version of jQuery, but `change()` does the trick. – Chad Hedgcock Jun 06 '18 at 21:43
  • Thanks. This was the only way it worked for me (after trying everything else above this). – inspirednz Mar 08 '20 at 03:18
  • Accepted answer was also right But in that on change event was not working. And with this method. On change event is also working. – LOKESH Sep 16 '20 at 09:41
  • the .change() has a magic affect to let this solution work inside bootstrap modal – Mahmoud Apr 08 '22 at 13:25
53

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;
mattsson
  • 1,132
  • 12
  • 18
24

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");
Clyde
  • 732
  • 8
  • 19
9

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;
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
salah9
  • 502
  • 1
  • 10
  • 21
6

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");
MAXE
  • 4,978
  • 2
  • 45
  • 61
Asif Ramzan
  • 61
  • 1
  • 1
3

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

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

OR

$('select').prop('selectedIndex', 3);
Makyen
  • 31,849
  • 12
  • 86
  • 121
Dilip Kumar Yadav
  • 565
  • 1
  • 7
  • 27
  • 1
    Your profile indicates you're associated with the link you had included here. Linking to something you're affiliated with (e.g. a product or website) without disclosing that affiliation *in your post* is considered spam on Stack Exchange/Stack Overflow. See: [**What signifies "Good" self promotion?**](//meta.stackexchange.com/q/182212), [some tips and advice about self-promotion](/help/promotion), [What is the exact definition of "spam" for Stack Overflow?](//meta.stackoverflow.com/q/260638), and [What makes something spam](//meta.stackexchange.com/a/58035). – Makyen Apr 29 '19 at 04:15
  • The second example is the only thing on the page that's worked so far for me – Bbb Sep 08 '20 at 18:07
3

set value and update dropdown list event

$("#id").val("1234").change();
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
3

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();
Mannu saraswat
  • 1,061
  • 8
  • 15
1

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.

JapineJ
  • 29
  • 4
0

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)
}
Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48
GrvTyagi
  • 4,231
  • 1
  • 33
  • 40
0

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.

vishwakarma09
  • 254
  • 3
  • 17
0

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

Rahul Gupta
  • 9,775
  • 7
  • 56
  • 69
0

//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);
Sikha
  • 81
  • 1
  • 2
0

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>
0

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.

0
//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())
})
0

Set the option by mentioning the value (eg: optionValue) & call the change event of the particular dropdown list (eg: drpDwnListId).

$("#drpDwnListId").val("optionValue").trigger("change");
Akila Supun
  • 21
  • 3
  • 8