54

I have been using the following code (with jQuery v1.4.2) to set the 'selected' attribute of a select list based on its 'text' description rather than its 'value':

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

This code worked fine, until I noticed one select list on which it failed, depending on the text that was being matched. After some hair-pulling I realized that it was failing only in cases where the text was a single word (no spaces, no non-alpha characters). (All of my previous uses of this code had worked fine with select lists comprised solely of multi-word chemical names.)

For example, within the one select list, it worked fine with:
pharbitic acid
25-D-spirosta-3,5-diene
pogostol (#Pogostemon#)

It failed with:
glucose
adenine

I have tried any way I could think of to surround the text variable with quotes (both single and double) to no avail. (But why should a single word need quotes when a two word phrase does not?)

I have tried hard coding the text in there and had the same result.

This works:

$("#constituent option[text=#a#-allocryptopine]").attr('selected', 'selected');
  

This works:

$("#constituent option[text=5-O-methylrisanrinol]").attr('selected', 'selected');

This did not work:

$("#constituent option[text=adenine]").attr('selected', 'selected');

I tried hard coding quotes. This did not work:

$("#constituent option[text='glucose']").attr('selected', 'selected');

I could not get hard coded quotes (single or double) to work with any text at all.

It's worth noting that quotes are acceptable when using the 'value' attribute. E.g., both of these work fine:

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

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

Below is some code to demonstrate the problem. Two select lists, the first of which is comprised of simple words, the second of two word phrases. When the page loads it tries to set the value of each select list. The jQuery code works for the second list but not the first. (I tried putting a space in 'monkey' to get 'mon key' and it worked!)

A working demo of the code below is here.

I would greatly appreciate any insight into what I am doing wrong here. Or even an alternative selector syntax for using the 'text' attribute.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 

<head>
    
  <script type="text/javascript" src="../js/jquery/jquery.js"></script>
    
  <script type="text/javascript">
    
  $(document).ready(function(){

    var text1 = 'Monkey';
    $("#mySelect1 option[text=" + text1 + "]").attr('selected', 'selected');
        
    var text2 = 'Mushroom pie';
    $("#mySelect2 option[text=" + text2 + "]").attr('selected', 'selected');        
    
  });
    
  </script> 

</head>

<body>

  <select id="mySelect1">
    <option></option>
    <option>Banana</option>
    <option>Monkey</option>
    <option>Fritter</option>
  </select> 

  <select id="mySelect2">
    <option></option>
    <option>Cream cheese</option>
    <option>Mushroom pie</option>
    <option>French toast</option>
  </select> 

</body>

</html>
starball
  • 20,030
  • 7
  • 43
  • 238
Stuart Allen
  • 1,537
  • 1
  • 10
  • 19
  • Is there a reason you cannot simply set the selected index of the list? Selecting based on the text value isn't really the best way to do this. – casablanca Sep 05 '10 at 00:17
  • I get your point, but I don't know the index value at the time. Basically I build a table of data from a database, the user can edit a row by clicking on it and a number of select lists below are filled with the values from the table (this is what I use the code above for). Different values can be selected from one or more lists, then the database and table are updated using $.ajax. The select list index values are id values from the database tables. In theory I could store these invisibly in the table along with the text descriptions but I am trying to cut down on overhead where possible. – Stuart Allen Sep 05 '10 at 00:30

12 Answers12

118

When an <option> isn't given a value="", the text becomes its value, so you can just use .val() on the <select> to set by value, like this:

var text1 = 'Monkey';
$("#mySelect1").val(text1);

var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);

You can test it out here, if the example is not what you're after and they actually have a value, use the <option> element's .text property to .filter(), like this:

var text1 = 'Monkey';
$("#mySelect1 option").filter(function() {
    return this.text == text1; 
}).attr('selected', true);

var text2 = 'Mushroom pie';
$("#mySelect2 option").filter(function() {
    return this.text == text2; 
}).attr('selected', true);​

You can test that version here.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Thanks so much for your quick response. Just what I was after. (I do in fact have values set in the actual code.) I'd still be very much interested if anyone has any idea why my original code seemed to fail as it did in particular circumstances... – Stuart Allen Sep 05 '10 at 00:35
  • @Snubian - was the casing and such correct? The match will be case-sensitive – Nick Craver Sep 05 '10 at 00:51
  • I'm positive that the casing was fine, the code was failing only in very specific circumstances as I've tried to describe. And I've tested with hard-coding values as described above. The failure of the "Monkey" example in my test code seems to indicate that this usage fails in certain cases. Running the code on jsFiddle, you can see if you simply put a space in "Mon key", both the text1 variable and in the list option, it suddenly works. – Stuart Allen Sep 05 '10 at 01:07
  • +1 I needed to match the option value instead of the label text. It is achieved with `return this.val() == text2;` – Dylan Valade Mar 18 '13 at 14:25
  • 13
    Modern readers should note that this answer is out of date; using `.attr('selected', true);` will fail in jQuery 1.9+ and has been deprecated since jQuery 1.6. You should use `.prop('selected', true)` instead. See http://stackoverflow.com/a/496126/1709587 – Mark Amery May 24 '14 at 11:00
  • why you did not give the case [When an – Yahya Yahyaoui May 16 '17 at 15:39
  • @Stuart Allen: Is it possible you didn't have UNIQUE pairs (value AND text) for the options that failed? I had a problem selecting an option based on its text using ANY of the methods on this page. It turned out the problem was that the value attribute for the option I was trying to select was not unique. So even though I was selecting based on "xyz" as the text of an option, there was ANOTHER option ("uvw") that had the same VALUE as that one. When I made the VALUES unique, I was able to select based on the text (even though the text was always unique!) – user1693404 Nov 24 '20 at 20:32
26
$("#my-select option:contains(" + myText +")").attr("selected", true);

This returns the first option containing your text description.

Deivide
  • 529
  • 8
  • 14
15

try this:

$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
ScottE
  • 21,530
  • 18
  • 94
  • 131
4

Using the filter() function seems to work in your test cases (tested in Firefox). The selector would look like this:

$('#mySelect1 option').filter(function () {
    return $(this).text() === 'Banana';
});
wsanville
  • 37,158
  • 8
  • 76
  • 101
3

I usually use:

$("#my-Select option[text='" + myText +"']").attr("selected","selected") ;
Ly Thanh Ngo
  • 394
  • 1
  • 2
  • 15
2

In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript

document.getElementById("The id of the element").value = "The value"

And that would set the value and make the current value selected in the combo box. Tested in firefox.

it was easier than keep googling a solution for jQuery

chepe263
  • 2,774
  • 22
  • 38
1

The following works for text entries both with and without spaces:

$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
Matt
  • 11
  • 1
0

I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.

$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());

another way of writing it in a more readable fasion:

var valofText = $("#my-Select" + " option").filter(function() {
    return this.text == myText
}).val();
$(ElementID).val(valofText);

Pseudocode:

$("#my-Select").val( getValOfText( myText ) );
user2561852
  • 97
  • 1
  • 2
0

We can do it by searching the text in options of dropdown list and then by setting selected attribute to true.

This code is run in every environment.

 $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected');
maxhb
  • 8,554
  • 9
  • 29
  • 53
Kaushik Das
  • 405
  • 1
  • 5
  • 12
0
setSelectedByText:function(eID,text) {
    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;
},
ash
  • 1
0

If you want to selected value on drop-down text bases so you should use below changes: Here below is example and country name is dynamic:

    <select id="selectcountry">
    <option value="1">India</option>
    <option value="2">Ireland</option>
    </select>
    <script>
     var country_name ='India'
     $('#selectcountry').find('option:contains("' + country_name + '")').attr('selected', 'selected');
    </script>
Community
  • 1
  • 1
Chirag Prajapati
  • 529
  • 6
  • 10
0

Effective and efficient way to set selected value in dropdown using your text value

 $("#id option").filter(function () {
     //may want to use $.trim in here
     return $(this).text() == customerName.trim();
 }).prop('selected', true);