把变量int选项选中

I'm trying to select an Select Option throuh jQuery with a PHP variable.

HTML

<div id="dom-target">
<?php 
    $output = $user->distritos;
    echo htmlspecialchars($output);
?>
</div>

jQuery

<script type="text/javascript">  
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
    jQuery('select[name="country"]').find('option:contains(" + myData + ")').attr("selected",true);    
</script>

But won't change, only if I replace option:contains(" + myData + ") by text, for example option:contains("123") it will select option with text "123"

What I'm doing wrong?

Thanks!

You are concatenating a string inside of find(). Consider these three parts of the string:

  1. option:contains("
  2. the value of myData
  3. ")

To build such a string, you'll need to close the single quote after the first part, append myData, and open the single quote again for the third part.

Otherwise, you're selecting an <option> that contains the string " + myData + ".

var $div = jQuery("#dom-target"),
    myData = $div.text();

jQuery('select').find('option:contains("' + myData + '")').prop("selected", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="dom-target">foo</div>

<select>
  <option>test</option>
  <option>option 2</option>
  <option>foo</option>
  <option>bar</option>
</select>

</div>