Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery set selected option by data-value

Tags:

jquery

select

I have this select

<select id="myselect>
  <option value="1" data-value="rome">First option</option>
  <option value="2" data-value="paris">Second option</option>
  <option value="3" data-value="london">Third option</option>
</select>

And I have my ajax function that on success must set selected by data-value

$.ajax({
   ...
   success: function(response) {
      // response.val is paris
      $("#myselect option[data-value=" + response.val +"]").attr("selected","selected");
   ...

But doesn't work because of "unrecognized expression"

like image 871
FireFoxII Avatar asked Jan 12 '17 12:01

FireFoxII


1 Answers

Your id "myselect is missing the closing ", it should be

<select id="myselect">
..
</select>

Use

      $("#myselect option[data-value='" + response.val +"']").attr("selected","selected");

Here's a fiddle:

https://jsfiddle.net/k38efh2o/

like image 50
james_bond Avatar answered Nov 14 '22 09:11

james_bond