547

I have a select control, and in a javascript variable I have a text string.

Using jQuery I want to set the selected element of the select control to be the item with the text description I have (as opposed to the value, which I don't have).

I know setting it by value is pretty trivial. e.g.

$("#my-select").val(myVal);

But I'm a bit stumped on doing it via the text description. I guess there must be a way of getting the value out from the text description, but my brain is too Friday afternoon-ed to be able to work it out.

Dan Atkinson
  • 11,391
  • 14
  • 81
  • 114
DanSingerman
  • 36,066
  • 13
  • 81
  • 92
  • 1
    @DanAtkinson was about to do the same myself. [tag:select] has absolutely nothing to do with this question. – thecoshman Jan 13 '14 at 09:18

22 Answers22

791

Select by description for jQuery v1.6+

var text1 = 'Two';
$("select option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text1;
}).prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>

jQuery versions below 1.6 and greater than or equal to 1.4

var text1 = 'Two';
$("select option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text1;
}).attr('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>

Note that while this approach will work in versions that are above 1.6 but less than 1.9, it has been deprecated since 1.6. It will not work in jQuery 1.9+.


Previous versions

val() should handle both cases.

$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<select>
  <option value="0">One</option>
  <option value="1">Two</option>
</select>
daaawx
  • 3,273
  • 2
  • 17
  • 16
Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • 6
    This feels like it shouldn't work (it appears it could be ambiguous) but it actually should work fine for me. Thanks. – DanSingerman Jan 30 '09 at 16:28
  • @HermanD: yes I suppose a method named "val" should not be selecting an option based on anything other than the "value" attribute. – Crescent Fresh Jan 30 '09 at 16:55
  • 71
    Note that jQuery 1.4 has now changed this behavior to select by `value` if the attribute has been specified, and only select by text if the `value` attribute is missing. So in this example `$('select').val('Two')` will select the second option in 1.3.x, but will do nothing in 1.4.x. – Crescent Fresh Mar 03 '10 at 19:34
  • 18
    So, what's the best way to do it in 1.4 now? – JR Lawhorne Apr 03 '10 at 06:38
  • how can i select the first value of the select input? – RicardO Dec 17 '10 at 06:59
  • 4
    In more recent versions of jQuery, .val('not-an-option-value') will reset the select to the first option. – dland May 03 '11 at 09:29
  • 5
    The first answer to this question appears to be the solution post 1.3.x http://stackoverflow.com/questions/3644449/jquery-setting-select-list-selected-based-on-text-failing-strangely – DA. Dec 20 '11 at 00:34
  • Shouldn't you be using .prop('selected', true) and not attr since attr should be used for setting the attribute value in the DOM and not the actual property of the object, which is what you're really trying to achieve here? I realize that jQuery has some hacks in place to fix this prior to 1.6 and post 1.6.1, however, that doesn't make it correct. The attr should remain as the initial attr value set on the elements, not the actual property of the object. – Jacob Thomason Dec 29 '12 at 05:34
  • @JacobThomason: probably. I didn't add the `attr` stuff (my original answer is going on 4 years old). Go ahead and edit, please. – Crescent Fresh Dec 29 '12 at 09:27
  • I wish jQuery incremented major revision when it broke backward compatibility. – Majid Fouladpour Jun 17 '13 at 12:05
  • @Crescent Fresh: as the text of two selects can be duplicate, just use `val()` instead of `text()`. For more optimization on `filter(function()` use `filter(function(i, el)` and on `$(this).text()` use `el.text`. – machineaddict Jul 22 '13 at 07:12
  • 3
    jQuery could have a built-in function to do that! It aims at simplifying DOM manipulation after all – Augustin Riedinger Jul 18 '14 at 16:05
  • $('source4').val('Stock'); does not work for my select named source4 – Sam Alexander Apr 22 '15 at 15:44
148

I haven't tested this, but this might work for you.

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });
spoulson
  • 21,335
  • 15
  • 77
  • 102
92

Try this...to select the option with text myText

$("#my-Select option[text=" + myText +"]").prop("selected", true);
erwaman
  • 3,307
  • 3
  • 28
  • 29
Jay Corbett
  • 28,091
  • 21
  • 57
  • 74
  • @spoulson's answer worked for me...I tried to do it without the .each – Jay Corbett Jan 30 '09 at 16:55
  • 2
    In many cases, this approach doesn't work unfortunately. I even had to resolve to classic `$("#my-Select option[text=" + myText +"]").get(0).selected = true;` style from time to time :(... – Gelmir Mar 06 '11 at 21:15
  • 2
    Make sure that you are first removing the selected attribute before re-setting, otherwise it will appear not to work (works for me in 1.9) – esse Mar 06 '13 at 06:42
  • 3
    @MarkW For 1.9, use `.prop` instead of `.attr`; the cause of the change is that in 1.9 jQuery disabled the old hacks that let you use `.attr` to change some DOM properties as well as HTML attributes. (Google `javascript dom properties vs attributes` if you don't know the distinction.) – Mark Amery Aug 04 '13 at 09:27
  • Updated answer to use `.prop('selected', true)` instead of `.attr('selected', 'selected')` for jQuery 1.9+ compatibility. – erwaman Jan 16 '20 at 04:30
52

I do it on this way (jQuery 1.9.1)

$("#my-select").val("Dutch").change();

Note: don't forget the change(), I had to search to long because of that :)

Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
ErazerBrecht
  • 1,583
  • 2
  • 20
  • 37
21
$("#myselect option:contains('YourTextHere')").val();

will return the value of the first option containing your text description. Tested this and works.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • Thanks - I think this might be the version I use, as I also need to have logic for when there is no matching text, and this seems the easiest mechanism, for being able to do that. – DanSingerman Jan 30 '09 at 17:17
  • 1
    bear in mind, it will get only the value for the first option matching the text. – Russ Cam Jan 30 '09 at 18:32
  • In addition, you could chain attr("selected","selected") onto the wrapped set instead of val() and this would work similar to CarolinaJay65's answer – Russ Cam Jan 30 '09 at 18:57
  • 3
    OP said _"**setting** value"_ not _"**getting** value"_ – alexandre-rousseau Oct 10 '17 at 13:01
15

To avoid all jQuery version complications, I honestly recommend using one of these really simple javascript functions...

function setSelectByValue(eID,val)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].value==val) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

function setSelectByText(eID,text)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].text==text) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}
Dave
  • 3,093
  • 35
  • 32
  • It enables the selection of an select option via value or text (depending on function called). For example: setSelectByValue('sausages','2'); Will find, and select, the option with value "2" in the selection object with an id of "sausages". – Dave May 08 '13 at 15:55
  • 2
    @Neal Uh... it answers the question? – Mark Amery Oct 27 '13 at 12:27
15

This line worked:

$("#myDropDown option:contains(myText)").attr('selected', true);
Saghir A. Khatri
  • 3,429
  • 6
  • 45
  • 76
Diego Unanue
  • 6,576
  • 8
  • 47
  • 67
12

I know this is an old post, but I couldn't get it to select by text using jQuery 1.10.3 and the solutions above. I ended up using the following code (variation of spoulson's solution):

      var textToSelect = "Hello World";

      $("#myDropDown option").each(function (a, b) {
            if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
        });

Hope it helps someone.

Losbear
  • 3,255
  • 1
  • 32
  • 28
7
 $("#Test").find("option:contains('two')").each(function(){
     if( $(this).text() == 'two' ) {
        $(this).attr("selected","selected");
     }
 });

The if statement does a exact match with "two" and "two three" will not be matched

aWebDeveloper
  • 36,687
  • 39
  • 170
  • 242
  • No, that's not what I meant. I think my comment was a bit unclear, so I just deleted it. I did upvote your answer though, because it worked for my situation. – Jagd Sep 20 '11 at 18:42
6

Easiest way with 1.7+ is:

$("#myDropDown option:text=" + myText +"").attr("selected", "selected"); 

1.9+

$("#myDropDown option:text=" + myText +"").prop("selected", "selected"); 

Tested and works.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
RParker
  • 99
  • 1
  • 5
  • 1
    Not in 1.9+ it doesn't. Since 1.6 you should be using `.prop` to change DOM properties, not `.attr` (which is for HTML/DOM attributes). See http://stackoverflow.com/q/5874652/1709587 – Mark Amery Aug 04 '13 at 09:30
  • I would use ("selected",true) instead of the truthy value of "selected" – mplungjan Jan 27 '15 at 12:22
6

Here is very simple way. plz use it

$("#free").val("y").change();
Pankaj Chauhan
  • 1,623
  • 14
  • 12
4

take a look at the jquery selectedbox plugin

selectOptions(value[, clear]): 

Select options by value, using a string as the parameter $("#myselect2").selectOptions("Value 1");, or a regular expression $("#myselect2").selectOptions(/^val/i);.

You can also clear already selected options: $("#myselect2").selectOptions("Value 2", true);

Kimtho6
  • 6,154
  • 9
  • 40
  • 56
Vitor Silva
  • 17,114
  • 8
  • 33
  • 27
3

Just on a side note. My selected value was not being set. And i had search all over the net. Actually i had to select a value after a call back from a web service, because i was getting data from it.

$("#SelectMonth option[value=" + DataFromWebService + "]").attr('selected', 'selected'); 
$("#SelectMonth").selectmenu('refresh', true);

So the refresh of the selector was was the only thing that i was missing.

Ammar Bukhari
  • 2,082
  • 2
  • 16
  • 16
2

I found that by using attr you would end up with multiple options selected when you didn't want to - solution is to use prop:

$("#myDropDown option:text=" + myText +"").prop("selected", "selected");

Chris Edwards
  • 3,514
  • 2
  • 33
  • 40
1
 $('#theYear').on('change', function () {
 FY = $(this).find('option:selected').text();
 $('#theFolders').each(function () {
     $('option:not(:contains(' + FY + '))', this).hide();
 });
 $('#theFolders').val(0);
});

$('#theYear').on('mousedown', function () {
 $('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
});
tomjm
  • 328
  • 2
  • 17
1

Very fiddly and nothing else seemed to work

$('select[name$="dropdown"]').children().text("Mr").prop("selected", true);

worked for me.

Netferret
  • 604
  • 4
  • 15
1

Try

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
<select id="mySelect">
  <option value="A">Text A</option>
  <option value="B">Text B</option>
  <option value="C">Text C</option>
</select>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

I had a problem with the examples above, and the problem was caused by the fact that my select box values are prefilled with fixed length strings of 6 characters, but the parameter being passed in wasn't fixed length.

I have an rpad function which will right pad a string, to the length specified, and with the specified character. So, after padding the parameter it works.

$('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));


function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
    pStr = pStr + pPadStr;
return pStr; 
} 
Keith
  • 781
  • 4
  • 11
  • 21
0

Heres an easy option. Just set your list option then set its text as selected value:

$("#ddlScheduleFrequency option").selected(text("Select One..."));
Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38
0

This accepted answer does not seem correct, while .val('newValue') is correct for the function, trying to retrieve a select by its name does not work for me, I had to use the id and classname to get my element

Sam Alexander
  • 504
  • 1
  • 6
  • 24
0

If you are trying to bind select with ID then the following code worked for me.

<select name="0product_id[]" class="groupSelect" id="groupsel_0" onchange="productbuilder.update(this.value,0);">
    <option value="0" class="notag" id="id0_0">--Select--</option>
    <option class="notag" value="338" id="id0_338"  >Dual Promoter Puromycin Expression Plasmid - pSF-CMV-PGK-Puro  > £114.00</option>
    <option class="notag" value="282" id="id0_282"  >EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00</option>
    <option class="notag" value="265" id="id0_265"  >FMDV IRES Puromycin Expression Plasmid - pSF-CMV-FMDV-Puro  > £114.00</option>
    <option class="notag" value="101" id="id0_101"  >Puromycin Selection Plasmid - pSF-CMV-Ub-Puro AscI  > £114.00</option>
    <option class="notag" value="105" id="id0_105"  >Puromycin Selection SV40 Ori Plasmid - pSF-CMV-Ub-Puro-SV40 Ori SbfI  > £114.00</option></select>

AND THIS IS TEH JS CODE

$( document ).ready(function() {
      var text = "EMCV IRES Puromycin Expression Plasmid - pSF-CMV-EMCV-Puro  > £114.00";
      alert(text);
$("#groupsel_0 option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == text;
}).prop('selected', true);
});
Dharman
  • 30,962
  • 25
  • 85
  • 135
Hafiz Siddiq
  • 671
  • 3
  • 9
  • 23
-1

Get the children of the select box; loop through them; when you have found the one you want, set it as the selected option; return false to stop looping.

geowa4
  • 40,390
  • 17
  • 88
  • 107