Home jQuery - setting the selected value of a select control via its text description
Reply: 19

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

DanSingerman
1#
DanSingerman Published in 2009-01-30 16:12:17Z

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.

Community
2#
Community Reply to 2017-05-23 12:34:53Z

Given this HTML:

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

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

Select by description for jQuery versions below 1.6 and greater than or equal to 1.4: https://stackoverflow.com/a/3644500/31532

var text1 = 'Two';
$("select option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == text1; 
}).attr('selected', true);

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

Select by description for previous versions:

val() should handle both cases. Are you not seeing it?

Eg:

$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"
spoulson
3#
spoulson Reply to 2009-01-30 16:22:59Z

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

$("select#my-select option")
   .each(function() { this.selected = (this.text == myVal); });
geowa4
4#
geowa4 Reply to 2009-01-30 16:23:15Z

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.

Russ Cam
5#
Russ Cam Reply to 2009-01-30 16:45:05Z
$("#myselect option:contains('YourTextHere')").val();

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

Josh Crozier
6#
Josh Crozier Reply to 2015-02-04 02:09:00Z

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

$("#my-Select option[text=" + myText +"]").attr("selected","selected");
Kimtho6
7#
Kimtho6 Reply to 2012-02-03 14:39:35Z

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

aWebDeveloper
8#
aWebDeveloper Reply to 2011-07-07 13:14:29Z
 $("#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

Keith
9#
Keith Reply to 2012-01-18 13:39:38Z

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; 
} 
mplungjan
10#
mplungjan Reply to 2015-01-27 12:21:42Z

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.

Dave
11#
Dave Reply to 2013-05-08 15:49:51Z

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;
}
Ammar Bukhari
12#
Ammar Bukhari Reply to 2013-06-01 07:33:25Z

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.

Chris Edwards
13#
Chris Edwards Reply to 2013-06-17 11:59:21Z

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

Losbear
14#
Losbear Reply to 2013-10-02 13:54:57Z

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.

Saghir A. Khatri
15#
Saghir A. Khatri Reply to 2014-07-03 05:40:16Z

This line worked:

$("#myDropDown option:contains(myText)").attr('selected', true);
tomjm
16#
tomjm Reply to 2014-09-16 14:22:24Z
 $('#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');
});
Misa Lazovic
17#
Misa Lazovic Reply to 2016-06-01 13:28:30Z

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

$("#ddlScheduleFrequency option").selected(text("Select One..."));
Sam Alexander
18#
Sam Alexander Reply to 2015-04-22 15:48:31Z

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

Jakub Matczak
19#
Jakub Matczak Reply to 2016-07-21 08:59:39Z

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

Pankaj Chauhan
20#
Pankaj Chauhan Reply to 2017-09-07 04:34:31Z

Here is very simple way. plz use it

$("#free").val("y").change();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.31492 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO