0

I need to programmatically set an option of an existing select box when I only know the text of the option and not the value.

Here is my code:

$("#" + eventQuestions[x].code).find('option[text="' + eventAnswers[x].vAnswerString + '"]').attr("selected");

Don't focus too much on selecting the right html element or the right text being inside the vAnswerString - I can confirm those are correct.

Basically the option is not being selected. What is wrong with my code?

btf
  • 173
  • 2
  • 11
  • 2
    is `text` an actual attribute value of the option, i.e., `` because if it is the second case, your selector will not work – chiliNUT May 28 '15 at 01:41
  • 2
    the attr function returns the current value of the attribute when not providing a second parameter. To add the selected attribute do $(**).attr("selected" , true) – paquino May 28 '15 at 01:41
  • 2
    Check here http://stackoverflow.com/questions/18317082/filter-elements-out-of-a-jquery-object-based-on-text-content – Allen Tellez May 28 '15 at 01:41
  • 2
    add a filter to your selector – Allen Tellez May 28 '15 at 01:42
  • 2
    http://stackoverflow.com/q/496052/771578 – messivanio May 28 '15 at 01:43
  • 1
    @chiliNUT It is the second case. Thanks for pointing that out. I will need to find how to select the option when I only know `` – btf May 28 '15 at 01:45
  • 2
    @btf NP. check out tellez's link, it references the jquery-only pseudo-selector `:contains` which is exactly what you need for this situation – chiliNUT May 28 '15 at 01:46

2 Answers2

2

Check out this answer.

You can use that filter to check the inner text and then you put the selected attribute like this:

.attr("selected", true);

Example I tested it with:

$(function() {
    $("#select").find("option").filter(function() {
        return this.innerHTML == "InnerText";
    }).attr("selected", true);
})
Community
  • 1
  • 1
Roberto Soares
  • 244
  • 1
  • 11
1

Here is a working example for jquery 1.6+.

Select the option using the filter function:

var text = "theTextToFind";
var matchingOption = $("select#myselect option").filter(function () {
        return $(this).text() == text;
    });

Set the value using the property function:

matchingOption.prop('selected', true);

Also check out this Answer.

Community
  • 1
  • 1
Brino
  • 2,442
  • 1
  • 21
  • 36