AJD AJD - 5 months ago 12x
Javascript Question

How do I set a select option with jquery if it matches the content in a span tag?

I have a dropdown select/option element that contains a list of artists:

<select id="taxonomy_dropdown_widget_dropdown_2" onchange="document.location.href=this.options[this.selectedIndex].value;" class="taxonomy_dropdown_widget_dropdown" name="taxonomy_dropdown_widget_dropdown_2">
<option value="">Browse Artists</option>
<option value="http://dev/artist-tag/a-aublet/">A. Aublet (1)</option>
<option value="http://dev/artist-tag/a-carie-baron/">A. Carie Baron (1)</option>

If you click one of the images by that artist you navigate to a single page. Located on that page is this html:

<span class="tagged_as"><span>Artist:</span> <a rel="tag" href="http://dev/artist-tag/a-aublet/">A. Aublet</a></span>

The name in the tag almost matches the name in the option select, but it doesn't have the (1).

I would like to use jquery to check the name on the page (.tagged_as a) and select the option that matches it.

Roughly here is what I want to do (but it doesn't work):

var artistName = document.querySelector("span.tagged_as > a");

if ( artistName ) {

var artistNamevalue = artistName.innerHTML ;

$('#taxonomy_dropdown_widget_dropdown_2 option').filter(function() {

return this.text == artistNamevalue;

}).attr('selected', true);


Here's the fiddle I'm trying: https://jsfiddle.net/1w4qx4ne/

The 'Browse Artists' dropdown should say: A. Aublet


Since you are not matching the artistName perfectly (you only need to check if the text contains a substring of the artistName), one solution is to use text.indexOf(). Here's the code:

$('#taxonomy_dropdown_widget_dropdown_2 option').filter(function() {
  return (this.text.indexOf(artistNamevalue) >= 0); 
}).attr('selected', 'selected');

Fiddle https://jsfiddle.net/1w4qx4ne/1/