1216

I have a select field with some options in it. Now I need to select one of those options with jQuery. But how can I do that when I only know the value of the option that must be selected?

I have the following HTML:

<div class="id_100">
  <select>
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>
  </select>
</div>

I need to select the option with value val2. How can this be done?

Here's a demo page: http://jsfiddle.net/9Stxb/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
w00
  • 26,172
  • 30
  • 101
  • 147

28 Answers28

1907

There's an easier way that doesn't require you to go into the options tag:

$("div.id_100 select").val("val2");

Check out this jQuery method.

Note: The above code does not trigger the change event. You need to call it like this for full compatibility:

$("div.id_100 select").val("val2").change();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pinghsien422
  • 19,836
  • 1
  • 20
  • 22
  • 23
    This may cause bugs in FF (at least) occuring in empty select box – Jonathan Jul 09 '14 at 14:36
  • 30
    the poster of the question starts with: "I have a select field with some options in it..." so it's not empty, therefore solution remains correct. – pinghsien422 Jul 10 '14 at 17:37
  • 1
    I faced the empty dropdown issue due to val() but it was resolved by using prop() or attr(). – Bikal Basnet Dec 25 '14 at 13:33
  • How would you achieve this if the value was empty? – Gareth Daine Mar 06 '15 at 11:52
  • What if the select has a multiple attribute set? I tried comma separating the values, but wont work.. – James Cazzetta Apr 21 '15 at 13:48
  • Wrt the issue of empty options or setting a value that is currently not in the options, I would say that your logic should detect and avoid this situation rather than having it fail silently. – pinghsien422 Jun 21 '15 at 11:31
  • 11
    @JamesCazzetta send an array to val: `.val(["Multiple2", "Multiple3"])`. http://api.jquery.com/val/#val-value – scipilot Jul 19 '15 at 05:36
  • 157
    I had to manually call `.val(x).change();` to trigger the select's onChange event, it seems setting val() doesn't fire it. – scipilot Jul 19 '15 at 05:48
  • 22
    Be careful: val() may set values that do not exist in options. – Daniel Apr 14 '16 at 11:33
  • 1
    This will try to set "val2" as the value of the entire select (which doesn't have any effect), but the question was how to select the option element where value is val2 - Am I missing something here? – BornToCode Aug 29 '16 at 13:49
  • 1
    This WILL NOT update the element's outerHTML property. If you need that property, this solution does not work. – HoldOffHunger Nov 16 '17 at 17:16
  • @scipilot 's tip is great, and I've found a lot of these hacky utilities that implement wrappers for select boxes to provide them with functionality they wouldn't otherwise need require calling the .change() after the .val() to work as intended. – conrad10781 Jan 18 '18 at 20:19
  • Using jQuery Mobile don't forget to update the UI so your selection displays. $('#select').selectmenu().selectmenu('refresh'); – Olmstov Feb 01 '18 at 17:56
  • 4
    If this is not working for you, remember that $("div.id_100 select") is selecting the
    element. For testing purposes, try: $('select').val(the_value); This is only if you have one
    – Exel Gamboa Jun 18 '18 at 20:31
  • I use query mobile and is necesary to use the trigger("change") to update the UI. Thanks – Kandy May 03 '21 at 15:34
545

To select an option with value 'val2':

$('.id_100 option[value=val2]').attr('selected','selected');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31
  • 11
    This is the best solution if the desired value may or may not be an option, and you don't want to make a change if it isn't an option. If you use `.val()` on the select and try to pick a value that isn't there it will deselect everything. – Wally Altman Jun 19 '14 at 19:44
  • Agree - this is the most elegant option - clear and to the point. Not sure if "prop" works better in all cases (browsers). But this certainly does the easy lookup for you. – Lee Fuller Nov 28 '15 at 21:35
  • 5
    Also, I have used __`$("select[name=foo] option[value=bar]).attr('selected','selected');`__ which also worked well for all browsers I tested. – Lee Fuller Nov 29 '15 at 17:18
  • Nice answer BUT, I find it to be inconsistent when dealing with large selects, randomly missing out elements, while .prop() produced a constant result. (Sample was around 4000 options in the select and the script needed to dynamically select anything between 1 and 4000). – Emil Borconi Apr 07 '16 at 10:31
  • Definitely needed to use `.attr('selected', true);` vs `prop()` in Safari at least. Surprising since I'd consider this a property but apparently not. – Brendon Muir Oct 10 '16 at 22:59
  • I like this answer because this allows me to set by custom attributes on options in my case I am not setting by value but a custom attribute. – Someone Dec 23 '16 at 14:57
  • This worked for me, but since my values where decimal values (for example .05, .1, .25) I had to use doble quotes around them like this $('.id_100 option[value="val2"]').attr('selected','selected'); – c0y0teX May 20 '17 at 17:25
  • 1
    I like this answer better than the accepted answer, because: element.outerHTML gets updated with this, whereas it does not with the accepted answer. – HoldOffHunger Nov 16 '17 at 17:16
  • As indicated by @LeeFuller, `.attr('selected', 'selected')` is better supported than the `.prop` way. Chrome ignored @A.Wolff's suggestion. – Alex Feb 20 '18 at 14:47
  • 4
    It's worth noting that this won't work if the select dropdown has been hidden, so in my case I'm using the select boxit plugin but trying to trigger select box change so original code with onchange handler for dropdown will still run. Just have to update code for new element which is selectboxit element – chris c Aug 29 '18 at 22:56
435

Use the change() event after selecting the value. From the documentation:

If the field loses focus without the contents having changed, the event is not triggered. To trigger the event manually, apply .change() without arguments:

$("#select_id").val("val2").change();

More information is at .change().

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jitendrapurohit
  • 9,435
  • 2
  • 28
  • 39
  • 35
    This deserves much more upvotes and belongs to the top. Its the proper way, no fiddling with `prop`, `attr` etc. and progagates all events properly. – Polygnome Mar 10 '17 at 12:49
  • 1
    Yes, this propagates all events correctly. In my testing, "attr" worked the first time, then everything stayed "selected". I used "prop" which changed everything correctly, but didn't propagate events such as (show/hide) other fields. This answer worked in all cases and should be considered correct. – iLLin Jun 26 '17 at 16:06
  • Got Error!!! This change calls all other dropdowns change events...How to avoid from calling other dropdowns change events – Daniel A Sathish Kumar Jul 25 '17 at 11:22
  • 3
    If you already have a listener bound to change this will cause an infinite loop. – qwertzman Oct 09 '17 at 11:36
  • Using jQuery Mobile you can update the UI without firing the change event by calling refresh. $('#select').selectmenu().selectmenu('refresh'); – Olmstov Feb 01 '18 at 17:57
72

Deselect all first and filter the selectable options:

$('.id_100 option')
     .removeAttr('selected')
     .filter('[value=val1]')
         .attr('selected', true)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
silly
  • 7,789
  • 2
  • 24
  • 37
  • 2
    The value of the selected attribute can be an empty string or `selected`. Did you mean `.prop()`? – rink.attendant.6 Sep 17 '13 at 17:37
  • 3
    Good answer. Accepted answer ends with empty select, when the value doesn't exist in options. – Rauli Rajande Jan 31 '15 at 20:12
  • 5
    TO THE TOP, best one here. For future use I think we should use prop instead of attr. – Daniel Apr 14 '16 at 11:34
  • I like this solution a lot. I'm wondering though if it would be better, performance-wise, if the selector was changed to ".id_100 > option" – Hill Apr 20 '17 at 18:54
  • In my case, I had to use .prop('selected', true); instead of .attr('selected', true); and also I had to trigger select.change() event because it is not triggered automatically. – Sinan ILYAS Aug 19 '21 at 08:23
  • `.attr` was probably valid syntax in 2012, but shouldn't work these days as it's the property that needs to be changed, not the attribute. It should be `.prop()` – Auspex Oct 31 '22 at 16:22
47
<select name="contribution_status_id" id="contribution_status_id" class="form-select">
    <option value="1">Completed</option>
    <option value="2">Pending</option>
    <option value="3">Cancelled</option>
    <option value="4">Failed</option>
    <option value="5">In Progress</option>
    <option value="6">Overdue</option>
    <option value="7">Refunded</option>
</select>

Setting to Pending status by value:

$('#contribution_status_id').val("2");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Developer
  • 3,857
  • 4
  • 37
  • 47
44

For me the following did the job

$("div.id_100").val("val2").change();
Taran
  • 12,822
  • 3
  • 43
  • 47
33

I think the easiest way is selecting to set val(), but you can check the following. See How to handle select and option tag in jQuery? for more details about options.

$('div.id_100  option[value="val2"]').prop("selected", true);

$('id_100').val('val2');

Not optimised, but the following logic is also useful in some cases.

$('.id_100 option').each(function() {
    if($(this).val() == 'val2') {
        $(this).prop("selected", true);
    }
});
Nizam
  • 4,569
  • 3
  • 43
  • 60
Dipu
  • 1,739
  • 1
  • 12
  • 3
  • I prefer this method over setting val() directly. I like to set the attribute too - helps with debugging. $(this).attr("selected","selected") – Craig Jacobs Jan 01 '18 at 23:19
33

The best way is like this:

$(`#YourSelect option[value='${YourValue}']`).prop('selected', true);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • On chrome, setting `$(' – Joshua Burns Dec 13 '19 at 01:10
  • Although this will work too but $(' – QMaster Dec 22 '19 at 20:24
24

You can achieve this with different methods (remember if an element is to be operated, better give it an id or class, rather than having its parent element be an id or class):

Here,, as the div has a class to target the select inside it, the code will be:

$("div.id_100 select").val("val2");

or

$('div.id_100  option[value="val2"]').prop("selected", true);

If the class would have been given to select itself, the code will be:

$(".id_100").val("val2");

or

$('.id_100 option[value=val2]').attr('selected','selected');

or

$('.id_100 option')
    .removeAttr('selected')
    .filter('[value=val1]')
    .attr('selected', true);

To pass the value dynamically, code will be:

valu="val2";

$("div.id_100 select").val(valu);
$("div.id_100 > select > option[value=" + valu + "]").prop("selected",true);

If element is added through Ajax, you will have to give 'id' to your element and use:

window.document.getElementById

Else you will have to give 'class' to your element and use

window.document.getElementById

You can also select the value of the select element by its index number.

If you have given ID to your select element, the code will be:

window.document.getElementById('select_element').selectedIndex = 4;

Remember when you change the select value as said above, the change method is not called.

I.e., if you have written code to do some stuff on change of select the above methods will change the select value but will not trigger the change.

To trigger the change function, you have to add .change() at the end.

So the code will be:

$("#select_id").val("val2").change();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sifr_dot_in
  • 3,153
  • 2
  • 33
  • 42
23

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue], so in your case you can select the option and set the selected attribute.

$("div.id_100 > select > option[value=" + value + "]").prop("selected",true);

Where value is the value you wish to select by.

If you need to removed any prior selected values, as would be the case if this is used multiple times you'd need to change it slightly so as to first remove the selected attribute

$("div.id_100 option:selected").prop("selected",false);
$("div.id_100 option[value=" + value + "]")
        .prop("selected",true);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rune FS
  • 21,497
  • 7
  • 62
  • 96
21

A simple answer is, in HTML:

<select name="ukuran" id="idUkuran">
    <option value="1000">pilih ukuran</option>
    <option value="11">M</option>
    <option value="12">L</option>
    <option value="13">XL</option>
</select>

In jQuery, call the below function by a button or whatever

$('#idUkuran').val(11).change();

It is simple and 100% works, because it's taken from my work... :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mang Jojot
  • 400
  • 4
  • 12
20

There isn't any reason to overthink this. All you are doing is accessing and setting a property. That's it.

Okay, so some basic DOM:

If you were doing this in straight JavaScript, it you would this:

window.document.getElementById('my_stuff').selectedIndex = 4;

But you're not doing it with straight JavaScript, you're doing it with jQuery. And in jQuery, you want to use the .prop() function to set a property, so you would do it like this:

$("#my_stuff").prop('selectedIndex', 4);

Anyway, just make sure your id is unique. Otherwise, you'll be banging your head on the wall wondering why this didn't work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yitzhak
  • 551
  • 6
  • 12
15

The easiest way to do that is:

HTML

<select name="dept">
   <option value="">Which department does this doctor belong to?</option>
   <option value="1">Orthopaedics</option>
   <option value="2">Pathology</option>
   <option value="3">ENT</option>
</select>

jQuery

$('select[name="dept"]').val('3');

Output: This will activate ENT.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pran
  • 1,817
  • 23
  • 23
14

It's better to use change() after setting select value.

$("div.id_100 select").val("val2").change();

By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:

JS Fiddle

Nick Tsai
  • 3,799
  • 33
  • 36
  • Why is this? Could you explain a bit? – 71GA Aug 04 '17 at 21:27
  • [JS Fiddle](http://jsfiddle.net/9Stxb/2838/). With a change() method, the code will close to changing select by user, while there are on-change listeners needed to be handle. – Nick Tsai Aug 05 '17 at 02:39
14

$('#graphtype option[value=""]').prop("selected", true);

This works well where #graphtype is the id of the select tag.

Example select tag:

<select name="site" id="site" class="form-control" onchange="getgraph1(this.options[this.selectedIndex].value);">
   <option value="" selected>Site</option>
   <option value="sitea">SiteA</option>
   <option value="siteb">SiteB</option>
 </select>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
LOKENDRA
  • 384
  • 3
  • 13
11

Use:

$("div.id_100 > select > option[value=" + value + "]").attr("selected",true);

This works for me. I'm using this code for parsing a value in a fancybox update form, and my full source from app.js is:

jQuery(".fancybox-btn-upd").click(function(){
    var ebid = jQuery(this).val();

    jQuery.ajax({
        type: "POST",
        url: js_base_url+"manajemen_cms/get_ebook_data",
        data: {ebookid:ebid},
        success: function(transport){
            var re = jQuery.parseJSON(transport);
            jQuery("#upd-kategori option[value="+re['kategori']+"]").attr('selected',true);
            document.getElementById("upd-nama").setAttribute('value',re['judul']);
            document.getElementById("upd-penerbit").setAttribute('value',re['penerbit']);
            document.getElementById("upd-tahun").setAttribute('value',re['terbit']);
            document.getElementById("upd-halaman").setAttribute('value',re['halaman']);
            document.getElementById("upd-bahasa").setAttribute('value',re['bahasa']);

            var content = jQuery("#fancybox-form-upd").html();
            jQuery.fancybox({
                type: 'ajax',
                prevEffect: 'none',
                nextEffect: 'none',
                closeBtn: true,
                content: content,
                helpers: {
                    title: {
                        type: 'inside'
                    }
                }
            });
        }
    });
});

And my PHP code is:

function get_ebook_data()
{
    $ebkid = $this->input->post('ebookid');
    $rs = $this->mod_manajemen->get_ebook_detail($ebkid);
    $hasil['id'] = $ebkid;
    foreach ($rs as $row) {
        $hasil['judul'] = $row->ebook_judul;
        $hasil['kategori'] = $row->ebook_cat_id;
        $hasil['penerbit'] = $row->ebook_penerbit;
        $hasil['terbit'] = $row->ebook_terbit;
        $hasil['halaman'] = $row->ebook_halaman;
        $hasil['bahasa'] = $row->ebook_bahasa;
        $hasil['format'] = $row->ebook_format;
    }
    $this->output->set_output(json_encode($hasil));
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adityo
  • 111
  • 1
  • 3
10
var opt = new Option(name, id);
$("#selectboxName").append(opt);
opt.setAttribute("selected","selected");
dmvianna
  • 15,088
  • 18
  • 77
  • 106
Ravi Wadje
  • 1,145
  • 1
  • 10
  • 15
9

.attr() sometimes doesn't work in older jQuery versions, but you can use .prop():

$('select#ddlCountry option').each(function () {
    if ($(this).text().toLowerCase() == co.toLowerCase()) {
        $(this).prop('selected','selected');
        return;
    }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shujaath Khan
  • 1,304
  • 16
  • 22
9

There are lots of solutions here to change the selected value, but none of them worked for me as my challenge was slightly different than the OP. I have a need to filter another select drop down based on this value.

Most folks used $("div.id_100").val("val2").change(); to get it to work for them. I had to modify this slightly to $("div#idOfDiv select").val("val2").trigger("change").

This was not completely enough either, I also had to make sure I waited for the document to load. My full code looks like this:

$(document).ready(function() {
    $("div#idOfDiv select").val("val2").trigger("change");
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jAC
  • 3,155
  • 3
  • 18
  • 29
  • I use query mobile and is necesary to use the trigger("change") to update the UI. Thanks – Kandy May 03 '21 at 15:34
8

It works for me:

$("#id_100").val("val2");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user9972736
  • 121
  • 1
  • 2
6

This works for sure for Select Control:

$('select#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
    this.selected = true;
    return;
} });
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shujaath Khan
  • 1,304
  • 16
  • 22
5

Try this.

It is simple, yet effective, JavaScript + jQuery, the lethal combination.

SelectComponent:

<select id="YourSelectComponentID">
    <option value="0">Apple</option>
    <option value="2">Banana</option>
    <option value="3">Cat</option>
    <option value="4">Dolphin</option>
</select>

Selection:

document.getElementById("YourSelectComponentID").value = 4;

Now your option 4 will be selected. You can do this, to select the values on start by default.

$(function(){
   document.getElementById("YourSelectComponentID").value = 4;
});

Or create a simple function put the line in it and call the function on anyEvent to select the option

A mixture of jQuery + JavaScript does the magic...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Majid Ali Khan
  • 701
  • 8
  • 13
5

Here is one simple function what acts like a jQuery plugin.

    $.fn.selectOption = function(val){
        this.val(val)
        .find('option')
        .removeAttr('selected')
        .parent()
        .find('option[value="'+ val +'"]')
        .attr('selected', 'selected')
        .parent()
        .trigger('change');

        return this;
    };

You just simply can do something like this:

$('.id_100').selectOption('val2');

The reason why using this is because you change the selected statement into the DOM what is cross-browser supported and also will trigger change to you can catch it.

It is basically a human action simulation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78
4

Thanks to silly's answer:

In my case, I needed to use a combination of

$('.id_100 option')
     .removeAttr('selected')
     .filter('[value=val1]')
         .prop('selected', true);

$('.id_100').val("val1").change(); // I need to set the same value here for my next form submit.

to set the correct value for my next form submission. When using this, even if I have another on change event bounded, it is not giving an infinite loop.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kevin Chan
  • 148
  • 9
3

There seems to be an issue with select drop down controls not dynamically changing when the controls are dynamically created instead of being in a static HTML page.

In jQuery this solution worked for me.

$('#editAddMake').val(result.data.make_id);
$('#editAddMake').selectmenu('refresh');

Just as an addendum, the first line of code without the second line, did actually work transparently in that, retrieving the selected index was correct after setting the index and if you actually clicked the control, it would show the correct item, but this didn't reflect in the top label of the control.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2288580
  • 2,210
  • 23
  • 16
3

An issue I ran into when the value is an ID and the text is a code. You cannot set the value using the code but you don't have direct access to the ID.

var value;

$("#selectorId > option").each(function () {
  if ("SOMECODE" === $(this).text()) {
    value = $(this).val();
  }
});

//Do work here
danesh
  • 39
  • 6
wattry
  • 936
  • 10
  • 22
2

I needed to select an option but it was possible for two options to have the same value.
This was purely for visual (front-end) difference.
You can select an option (even if 2 have the same value) like so:

let options = $('#id_100 option')
options.prop('selected', false)   // Deselect all currently selected ones
let option = $(options[0])        // Select option from the list
option.prop('selected', true)
option.parent().change()          // Find the <select> element and call the change() event.

This deselects all currently selected <option> elements. Selects the first (using options[0]) and updates the <select> element using the change event.

Kerwin Sneijders
  • 750
  • 13
  • 33
0

I have prepared a small JQuery extension that removes all unnecessary options and hides the selected option, the user sees only one value in the select field

$.prototype.makeReadOnly = function (canClick = false) {
    $(this).each(function () {
        $(this).readonly = true;
        if ($(this).is("select")) {
            if(!canClick) $(this).mousedown(function () { event.preventDefault(); }).keydown(function () { event.preventDefault(); });
            $(this).find('option:not(:selected)').remove();
            $(this).find('option').hide();
        }
    });
}

and then you can make all selects read-only

$("select").makeReadOnly();

or selects only with a specific read-only class

$("select.read-only").makeReadOnly();
Jerzy Gebler
  • 929
  • 9
  • 13