Steevie
Steevie

Reputation: 680

Set a jQuery UI selectmenu to a specific option by javascript

I have a selectmenu like the following

<select name="scale" id="scale">
  <option selected>linear</option>
  <option>root</option>
  <option>square</option>
</select>

To make it nice I use jQuery UI v1.11.2.

$('#scale').selectmenu();

I can now read the value of the dropdown by

alert($('#scale').val());

which results in 'linear' as the answer. I can also set the value to 'square' by using

$('#scale').val('square');
alert($('#scale').val());

which correctly gives the answer 'square'. But (!!!) the dropdown does not display this on the screen. So actually I can set and read the value, but the visual representation doesn't change - the widget does not refresh. I read somewhere to throw a .change() but without any effect. I also tried answers like in jQuery UI Selectmenu value set dynamically does not change visible selected value but failed. Any $('#scale').selectmenu('value', 'square'); resuts in the error message Error: no such method 'value' for selectmenu widget instance.

Can anyone help how to refresh the widget after setting it to a new value?

Upvotes: 32

Views: 33287

Answers (1)

blgt
blgt

Reputation: 8205

It should work as you expect it to if you just call refresh after using .val():

$('#scale').val('square');
$("#scale").selectmenu("refresh");

The reason for this is that the .val() function is provided by jQuery, while the widget is part of jQueryUI. [presumably the $.ui authors didn't want to alter the $ functionality, though this is purely speculation on my part]

Upvotes: 75

Related Questions