Jose Bernhardt Jose Bernhardt - 2 months ago 18
Javascript Question

Select option with cheerio (jquery) by text

I'm trying to select an option from a select dropdown with the

text()
attribute of the HTML element with
cheerio
. So far what I'm doing is that I'm trying to set the
attr
as selected matching, the element with the specific text.

This is what I'm trying:

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


I'm not getting any changes on the html when I do this. I print the html document on the console after doing this operation and I don't see that the option has changed to the one I'm selecting. Any idea why is not working or another workaround?

Answer

You can use the :contains filter to get the specific option element based on the text and set the value of the select element to it's value:

$('#s1').val($("#s1 option:contains('Val B')").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1">
  <option value="a">Val A</option>
  <option value="b">Val B</option>
</select>