624

If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

<div class="selDiv">
  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>
</div>


  • $("#my_select").val("the_new_value").change(); ... ... from so - dsdsdsdsd

19 답변


1075

A selector to get the middle option-element by value is

$('.selDiv option[value="SEL1"]')

For an index:

$('.selDiv option:eq(1)')

For a known text:

$('.selDiv option:contains("Selection 1")')

EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:

$('.selDiv option:eq(1)').prop('selected', true)

In older versions:

$('.selDiv option:eq(1)').attr('selected', 'selected')

EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selector to match the full text, but a filter works:

 $('.selDiv option')
    .filter(function(i, e) { return $(e).text() == "Selection 1"})

EDIT3: Use caution with $(e).text() as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no </option> tag):

<select ...>
<option value="1">Selection 1
<option value="2'>Selection 2
   :

If you simply use e.text any extra whitespace like the trailing newline will be removed, making the comparison more robust.


  • :contains is not great as it will match pieces of text; problematic if any of your option text is a substring of another option text. - Ryan
  • This is works too $('#id option[value="0"]').attr('selected', 'selected'); - DevC
  • @Grastveit how to change the color of first option if it is selected or not when it has a class say myClass. Thanks - Zaker
  • @User I don't understand. Maybe post it in a new question? Or is it $('.selDiv .myClass').css('color', 'red')? - Grastveit
  • I'd like to add you should DEFINITELY use prop and not attr. I almost went nuts trying to debug an application and changing from attr to prop fixed it. - user609926

109

None of the methods above provided the solution I needed so I figured I would provide what worked for me.

$('#element option[value="no"]').attr("selected", "selected");


  • Note as of jQuery 1.6 this should use prop and not attr. - Gone Coding
  • @GoneCoding Using .attr is correct. "selected" is an attribute of the <option> w3.org/TR/html5/forms.html#attr-option-selected - Carlos Llongo
  • @CarlosLlongo: That is irrelevant. The jQuery recommendation is to always use prop in preference to attr. That saves having to look up each and every property on w3.org in order to see if it is only an attribute, or implemented with backing actions. - Gone Coding

71

You can just use val() method:

$('select').val('the_value');


  • This is wrong because you are SETTING the value of ALL the SELECT elements to the_value. .val is not selector/filter function! It is a property accessor and passing it that string SETS the value. I tried to take my upvote back but was too late after I reallized this in testing. - AaronLS
  • Hot have you got 10 votes as useful answer? The val() is a getter and a setter. If you just use val(), you'll get the value. If you pass something like val('the_value') you're setting it to 'the_value' - Gui
  • Please @AaronLS and @guilhermeGeek, refer to the docs (last example). It works as a selector for select, checkboxes and radio buttons, and as a value setter for text inputs and textareas. - Leandro Ardissone
  • You have misread the documentation. For checkboxes, radios, and listboxes the command sets the "selected" attribute for those items. The last example shows how passing val("checkbox 1") causes it to become selected. This is not the same as a "selector" in terms of getting the objects via CSS/jquery selector. I tested your code, it doesn't work bottom line. - AaronLS
  • +1: no, it's not a JQuery selector, however I think most people searching for this question are like me, and simply want to change the currently selected option; coming up with an actual selector is merely a way to do that. And this is certainly better than answers that I've seen that have you iterate over all of the options. - kdgregory

47

By value, what worked for me with jQuery 1.7 was the below code, try this:

$('#id option[value=theOptionValue]').prop('selected', 'selected').change();


  • I'm not sure you need the .change() method. - Phillip Senn
  • The .change() was necessary. I had an example where I was switching thumbnails based on a SELECT. When I uploaded a custom theme, it was supposed to select "Custom Theme" from the list of options. The .prop() call worked, but without the .change(), the thumbnail image on the right of my select never updated. - Volomike
  • .change() was the best advise. +1 - Ja8zyjits
  • Note: a boolean prop value generates the same output. e.g. .prop('selected', true) - Gone Coding
  • Depends, some browsers - maybe old browsers - need of the string 'selected'. I think the majority of them support the text string. - mpoletto

12

You could name the select and use this:

$("select[name='theNameYouChose']").find("option[value='theValueYouWantSelected']").attr("selected",true);

It should select the option you want.


12

There are a number of ways to do this, but the cleanest approach has been lost among the top answers and loads of arguments over val(). Also some methods changed as of jQuery 1.6, so this needs an update.

For the following examples I will assume the variable $select is a jQuery object pointing at the desired <select> tag, e.g. via the following:

var $select = $('.selDiv .opts');

Note 1 - use val() for value matches:

For value matching, using val() is far simpler than using an attribute selector: https://jsfiddle.net/yz7tu49b/6/

$select.val("SEL2");

The setter version of .val() is implemented on select tags by setting the selected property of a matching option with the same value, so works just fine on all modern browsers.

Note 2 - use prop('selected', true):

If you want to set the selected state of an option directly, you can use prop (not attr) with a boolean parameter (rather than the text value selected):

e.g. https://jsfiddle.net/yz7tu49b/

$option.prop('selected', true);  // Will add selected="selected" to the tag

Note 3 - allow for unknown values:

If you use val() to select an <option>, but the val is not matched (might happen depending on the source of the values), then "nothing" is selected and $select.val() will return null.

So, for the example shown, and for the sake of robustness, you could use something like this https://jsfiddle.net/1250Ldqn/:

var $select = $('.selDiv .opts');
$select.val("SEL2");
if ($select.val() == null) {
  $select.val("DEFAULT");
}

Note 4 - exact text match:

If you want to match by exact text, you can use a filter with function. e.g. https://jsfiddle.net/yz7tu49b/2/:

var $select = $('.selDiv .opts');
$select.children().filter(function(){
    return this.text == "Selection 2";
}).prop('selected', true);

although if you may have extra whitespace you may want to add a trim to the check as in

    return $.trim(this.text) == "some value to match";

Note 5 - match by index

If you want to match by index just index the children of the select e.g. https://jsfiddle.net/yz7tu49b/3/

var $select = $('.selDiv .opts');
var index = 2;
$select.children()[index].selected = true;

Although I tend to avoid direct DOM properties in favour of jQuery nowadays, to future-proof code, so that could also be done as https://jsfiddle.net/yz7tu49b/5/:

var $select = $('.selDiv .opts');
var index = 2;
$select.children().eq(index).prop('selected', true);

Note 6 - use change() to fire the new selection

In all the above cases, the change event does not fire. This is by design so that you do not wind up with recursive change events.

To generate the change event, if required, just add a call to .change() to the jQuery select object. e.g. the very first simplest example becomes https://jsfiddle.net/yz7tu49b/7/

var $select = $('.selDiv .opts');
$select.val("SEL2").change();

There are also plenty of other ways to find the elements using attribute selectors, like [value="SEL2"], but you have to remember attribute selectors are relatively slow compared to all these other options.


10

   $(elem).find('option[value="' + value + '"]').attr("selected", "selected");


  • Thank you for your post, but what does this answer add to the conversation that is not included in the accepted answers? - Edward
  • if there is an option already selected then this will fail as a drop-down can't have more than one item selected unless it is a multi-select. You need to do .prop('selected',true) - derekcohen

9

Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.

<html>
<head>
<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">

$(function() {
    $(".update").bind("click",      // bind the click event to a div
        function() {
            var selectOption = $('.selDiv').children('.opts') ;
            var _this = $(this).next().children(".opts") ;

            $(selectOption).find("option[index='0']").attr("selected","selected");
//          $(selectOption).find("option[value='DEFAULT']").attr("selected","selected");
//          $(selectOption).find("option[text='Default']").attr("selected","selected");


//          $(_this).find("option[value='DEFAULT']").attr("selected","selected");
//          $(_this).find("option[text='Default']").attr("selected","selected");
//          $(_this).find("option[index='0']").attr("selected","selected");

    }); // END Bind
}); // End eventlistener

</script>
</head>
<body>
<div class="update" style="height:50px; color:blue; cursor:pointer;">Update</div>
<div class="selDiv">
        <select class="opts">
            <option selected value="DEFAULT">Default</option>
            <option value="SEL1">Selection 1</option>
            <option value="SEL2">Selection 2</option>
        </select>
    </div>
</body>
</html>


7

Using jquery-2.1.4, I found the following answer to work for me:

$('#MySelectionBox').val(123).change();

If you have a string value try the following:

$('#MySelectionBox').val("extra thing").change();

Other examples did not work for me so that's why I'm adding this answer.

I found the original answer at: https://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu


6

I use this, when i know the index of the list.

$("#yourlist :nth(1)").prop("selected","selected").change();

This allows the list to change, and fire the change event. The ":nth(n)" is counting from index 0



5

i'll go with:-

$("select#my-select option") .each(function() { this.selected = (this.text == myVal); });


5

For setting select value with triggering selected:

$('select.opts').val('SEL1').change();

For setting option from a scope:

$('.selDiv option[value="SEL1"]')
    .attr('selected', 'selected')
    .change();

This code use selector to find out the select object with condition, then change the selected attribute by attr().


Futher, I recommend to add change() event after setting attribute to selected, by doing this the code will close to changing select by user.



4

Try this

you just use select field id instead of #id (ie.#select_name)

instead of option value use your select option value

 <script>
    $(document).ready(function() {
$("#id option[value='option value']").attr('selected',true);
   });
    </script>


3

/* This will reset your select box with "-- Please Select --"   */ 
    <script>
    $(document).ready(function() {
        $("#gate option[value='']").prop('selected', true);
    });
    </script>


3

For Jquery chosen if you send the attribute to function and need to update-select option

$('#yourElement option[value="'+yourValue+'"]').attr('selected', 'selected');
$('#editLocationCity').chosen().change();
$('#editLocationCity').trigger('liszt:updated');


2

try this new one

Exactly it will works

<script>    
    $(document).ready(function() {
    $("#id").val('select value here');
       });
        </script>


1

The $('select').val('the_value'); looks the right solution and if you have data table rows then:

$row.find('#component').val('All');


1

if you want to not use jQuery, you can use below code:

document.getElementById("mySelect").selectedIndex = "2";


1

Thanks for the question. Hope this piece of code will work for you.

var val = $("select.opts:visible option:selected ").val();

Linked


Related

Latest