Set select option 'selected', by value
Asked Answered
P

29

1233

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/

Picardi answered 12/11, 2012 at 12:16 Comment(0)
C
1937

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();
Cavalla answered 7/6, 2013 at 8:49 Comment(15)
This may cause bugs in FF (at least) occuring in empty select boxHaehaecceity
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.Cavalla
I faced the empty dropdown issue due to val() but it was resolved by using prop() or attr().Jubilate
How would you achieve this if the value was empty?Starobin
What if the select has a multiple attribute set? I tried comma separating the values, but wont work..Superannuation
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.Cavalla
@JamesCazzetta send an array to val: .val(["Multiple2", "Multiple3"]). api.jquery.com/val/#val-valueMendelsohn
I had to manually call .val(x).change(); to trigger the select's onChange event, it seems setting val() doesn't fire it.Mendelsohn
Be careful: val() may set values that do not exist in options.Arbitrament
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?Puppis
This WILL NOT update the element's outerHTML property. If you need that property, this solution does not work.Mudcat
@Mendelsohn '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.Shull
Using jQuery Mobile don't forget to update the UI so your selection displays. $('#select').selectmenu().selectmenu('refresh');Hedjaz
If this is not working for you, remember that $("div.id_100 select") is selecting the <div class="id-100"><select .../> element. For testing purposes, try: $('select').val(the_value); This is only if you have one <select> element in your page. Please, modify as needed. Also, remember to be sure that the element is in the DOM before the script runs.Hauberk
I use query mobile and is necesary to use the trigger("change") to update the UI. ThanksCarrell
F
552

To select an option with value 'val2':

$('.id_100 option[value=val2]').attr('selected','selected');
Flinger answered 12/11, 2012 at 12:17 Comment(10)
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.Teeth
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.Nobie
Also, I have used $("select[name=foo] option[value=bar]).attr('selected','selected'); which also worked well for all browsers I tested.Nobie
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).Jarrod
Definitely needed to use .attr('selected', true); vs prop() in Safari at least. Surprising since I'd consider this a property but apparently not.Files
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.Cannula
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');Cyanotype
I like this answer better than the accepted answer, because: element.outerHTML gets updated with this, whereas it does not with the accepted answer.Mudcat
As indicated by @LeeFuller, .attr('selected', 'selected') is better supported than the .prop way. Chrome ignored @A.Wolff's suggestion.Clothesline
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 elementSheree
T
439

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().

Twinflower answered 21/10, 2015 at 6:22 Comment(5)
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.Registrar
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.Porthole
Got Error!!! This change calls all other dropdowns change events...How to avoid from calling other dropdowns change eventsBearer
If you already have a listener bound to change this will cause an infinite loop.Laniary
Using jQuery Mobile you can update the UI without firing the change event by calling refresh. $('#select').selectmenu().selectmenu('refresh');Hedjaz
V
73

Deselect all first and filter the selectable options:

$('.id_100 option')
     .removeAttr('selected')
     .filter('[value=val1]')
         .attr('selected', true)
Vlad answered 12/11, 2012 at 12:20 Comment(6)
The value of the selected attribute can be an empty string or selected. Did you mean .prop()?Bohlin
Good answer. Accepted answer ends with empty select, when the value doesn't exist in options.Blount
TO THE TOP, best one here. For future use I think we should use prop instead of attr.Arbitrament
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"Swaney
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.Poetaster
.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()Ostium
A
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");
Abridge answered 5/12, 2013 at 17:27 Comment(0)
K
44

For me the following did the job

$("div.id_100").val("val2").change();
Kaon answered 27/7, 2016 at 13:27 Comment(0)
B
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);
    }
});
Blankenship answered 7/9, 2013 at 22:40 Comment(1)
I prefer this method over setting val() directly. I like to set the attribute too - helps with debugging. $(this).attr("selected","selected")Raber
C
33

The best way is like this:

$(`#YourSelect option[value='${YourValue}']`).prop('selected', true);
Coulee answered 11/3, 2019 at 17:55 Comment(2)
On chrome, setting $('<select>').val('asdf') did not update the select to show the currently selected option. This answer fixed that problem.Fishgig
Although this will work too but $('<select>').val('asdf') is working good in chrome 79.0.3945.88Washedout
I
26

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();
Interpellate answered 17/8, 2020 at 4:59 Comment(0)
P
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);
Participle answered 12/11, 2012 at 12:22 Comment(0)
B
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... :)

Brainstorming answered 9/12, 2017 at 17:13 Comment(2)
Your default value is 1000? Why not ""Jehial
it's an optional, you can modify as you need.. :)Brainstorming
C
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.

Creaky answered 3/3, 2018 at 9:41 Comment(0)
M
16

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.

Marsupium answered 2/12, 2015 at 7:23 Comment(0)
B
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

Butylene answered 6/6, 2017 at 8:56 Comment(2)
Why is this? Could you explain a bit?Kellam
JS Fiddle. With a change() method, the code will close to changing select by user, while there are on-change listeners needed to be handle.Butylene
M
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>
Mezzotint answered 16/1, 2018 at 6:51 Comment(0)
S
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));
}
Schmitz answered 16/3, 2014 at 8:42 Comment(0)
G
10
var opt = new Option(name, id);
$("#selectboxName").append(opt);
opt.setAttribute("selected","selected");
Gallantry answered 15/12, 2014 at 7:25 Comment(0)
C
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;
    }
});
Clang answered 8/9, 2016 at 4:40 Comment(0)
O
9

It works for me:

$("#id_100").val("val2");
Omniscient answered 6/4, 2020 at 12:55 Comment(0)
B
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");
});
Butte answered 8/3, 2021 at 1:24 Comment(1)
I use query mobile and is necesary to use the trigger("change") to update the UI. ThanksCarrell
C
6

This works for sure for Select Control:

$('select#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
    this.selected = true;
    return;
} });
Clang answered 26/11, 2015 at 5:2 Comment(0)
T
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...

Touristy answered 20/11, 2017 at 17:13 Comment(0)
C
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.

Calpac answered 16/1, 2018 at 9:58 Comment(0)
D
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.

Dishonest answered 9/3, 2022 at 16:0 Comment(0)
B
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.

Bugger answered 4/5, 2019 at 19:25 Comment(0)
S
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
Selffulfillment answered 14/8, 2019 at 17:31 Comment(0)
S
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.

Sneakbox answered 20/5, 2021 at 17:5 Comment(0)
L
1

Just use this line. Put the "option value id" you want to make it selected in val()

$('#select_id').val(your_option_value).change();
Lacuna answered 10/10, 2023 at 20:47 Comment(0)
C
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();
Cully answered 4/1, 2023 at 15:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.