1084
votes

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/

26

26 Answers

1722
votes

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

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

Check out the 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();
485
votes

To select an option with value 'val2':

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

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

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

60
votes

Deselect all first and filter the selectable options:

$('.id_100 option')
     .removeAttr('selected')
     .filter('[value=val1]')
         .attr('selected', true)
45
votes
<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>

Setting to Pending Status by value

   $('#contribution_status_id').val("2");
37
votes

For me the following did the job

$("div.id_100").val("val2").change();
29
votes

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);
    }
});
24
votes

Best way is like this:

$(`#YourSelect option[value='${YourValue}']`).prop('selected', true);
19
votes

a simple answer is, at 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>

on jquery, call below function by button or whatever

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

it simple and 100% works, coz its taken from my work... :) hope its help..

18
votes

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);
16
votes

There's no 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.

13
votes

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.

13
votes

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 it's parent element an id or class).
Here, As the div has a class to target the select inside it, 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, 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 value of select element by it's index number.
If you have given ID to your select element, code will be:

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

Remember when you change the select value as said above, 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.
for to trigger the change function you have to add .change() at the end. so the code will be:

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

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

12
votes

$('#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>
8
votes
var opt = new Option(name, id);
$("#selectboxName").append(opt);
opt.setAttribute("selected","selected");
8
votes

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));
}
7
votes

.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;
    }
});
4
votes

This works for sure for Select Control:

$('select#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
    this.selected = true;
    return;
} });
4
votes

it works for me

$("#id_100").val("val2");
3
votes

Try this. Simple yet effective javaScript + jQuery the lethal combo.

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

3
votes

Is old post but here is one simple function what act like 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 simple can do something like this:

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

Reson why use this is because you change selected satemant into DOM what is crossbrowser supported and also will trigger change to you can catch it.

Is basicaly human action simulation.

2
votes

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");
});

I hope this helps someone with the same challenge i had!

1
votes

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.

Hope this helps.

0
votes

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

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.