[javascript] jQuery - setting the selected value of a select control via its text description

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.

This question is related to javascript jquery

The answer is


This line worked:

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

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

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

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.


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.


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


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.


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

$("#myselect option:contains('YourTextHere')").val();

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


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.


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

Very fiddly and nothing else seemed to work

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

worked for me.


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


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.


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


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

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

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

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.


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

$("#myselect option:contains('YourTextHere')").val();

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


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

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

Very fiddly and nothing else seemed to work

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

worked for me.


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.


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

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

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

This line worked:

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

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


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.


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


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

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

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


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


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


Try

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

_x000D_
_x000D_
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
_x000D_
<select id="mySelect">
  <option value="A">Text A</option>
  <option value="B">Text B</option>
  <option value="C">Text C</option>
</select>
_x000D_
_x000D_
_x000D_


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


Here is very simple way. plz use it

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

Try

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

_x000D_
_x000D_
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
_x000D_
<select id="mySelect">
  <option value="A">Text A</option>
  <option value="B">Text B</option>
  <option value="C">Text C</option>
</select>
_x000D_
_x000D_
_x000D_


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


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

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

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.


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


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

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

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

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

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

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

Here is very simple way. plz use it

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

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

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

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


$("#myselect option:contains('YourTextHere')").val();

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


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.


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

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

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

$("#myselect option:contains('YourTextHere')").val();

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