553

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.

1
  • 1
    @DanAtkinson was about to do the same myself. select has absolutely nothing to do with this question. Commented Jan 13, 2014 at 9:18

24 Answers 24

798

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>

Sign up to request clarification or add additional context in comments.

13 Comments

This feels like it shouldn't work (it appears it could be ambiguous) but it actually should work fine for me. Thanks.
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.
So, what's the best way to do it in 1.4 now?
In more recent versions of jQuery, .val('not-an-option-value') will reset the select to the first option.
The first answer to this question appears to be the solution post 1.3.x stackoverflow.com/questions/3644449/…
|
149

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

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

Comments

93

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

$("#my-Select option[text=" + myText +"]").prop("selected", true);

6 Comments

@spoulson's answer worked for me...I tried to do it without the .each
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 :(...
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)
@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.)
Updated answer to use .prop('selected', true) instead of .attr('selected', 'selected') for jQuery 1.9+ compatibility.
|
54

I do it this way (jQuery 1.9.1)

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

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

4 Comments

Wish I could upvote multiple times. Its an hour past quitting time and now I can go home.
Great answer! short and simple...This should be on top...Keep voting up.
This worked in my case, thanks! But doesn't this select not by the displayed text, as the OP requested, but by the value itself, which the OP does not have?
$("#dropdown").val(varible).change(); is not working for me :(
23
$("#myselect option:contains('YourTextHere')").val();

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

4 Comments

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.
bear in mind, it will get only the value for the first option matching the text.
In addition, you could chain attr("selected","selected") onto the wrapped set instead of val() and this would work similar to CarolinaJay65's answer
OP said "setting value" not "getting value"
16

This line worked:

$("#myDropDown option:contains(myText)").attr('selected', true);

2 Comments

had to use prop('selected', true) for jQuery 1.12.3
Had to $("#myDropDown option").prop('selected', false); before, to unset any previous selected ones, or we'll have more that one item selected (use Inspector to check), that can lead to undesirable results.
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;
}

2 Comments

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".
@Neal Uh... it answers the question?
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.

Comments

8
 $("#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

1 Comment

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

2 Comments

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 stackoverflow.com/q/5874652/1709587
I would use ("selected",true) instead of the truthy value of "selected"
6

Here is very simple way. plz use it

$("#free").val("y").change();

1 Comment

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

Comments

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.

1 Comment

This is the right one - altough... i see no reason for the second line. Should work as is.
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");

Comments

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

Comments

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

Comments

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>

Comments

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

Comments

0

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

$("#ddlScheduleFrequency option").selected(text("Select One..."));

Comments

0

Very fiddly and nothing else seemed to work

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

worked for me.

2 Comments

This solution definitely works.
This sets the text of all the options, it doesn't match the option with the given text.
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);
});

Comments

0

Try this one ..

$("#my-select").val($("#my-select option:contains('searchText')").val()).change();

Comments

0

What worked for me was

$('#my-select').children().text("yourTextHere").prop("selected", true);

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.