Jose Bernhardt Jose Bernhardt - 1 year ago 142
Javascript Question

Select option with cheerio (jquery) by text

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

attribute of the HTML element with
. So far what I'm doing is that I'm trying to set the
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 Source

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=""></script>
<select id="s1">
  <option value="a">Val A</option>
  <option value="b">Val B</option>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download