How to disable specific jquery-ui selectmenu choices?

5.8k views Asked by At

I understand how to disable the entire selectmenu.

But I just want to disable a few of the options within it. How can I do it..?

1

There are 1 answers

0
T J On

The documentation reads:

The Selectmenu widgets provides a styleable select element replacement. It will act as a proxy back to the original select element, controlling its state for form submission or serialization

(emphasis mine).

Which means you can simply add the disabled attribute to the <option>'s you want to disable in the HTML and it'll be reflected in the widget once it is initialized.


Regarding the the changes you make dynamically to the original <select> element, it will not be reflected immediately in the widget - because as one can possibly imagine, constantly querying the DOM for changes in the original <select> is likely to cause a performance hit.

Hence we have the following:

refresh

Parses the original element and re-renders the menu. Processes any or elements that were added, removed or disabled.

All we have to do is, make the changes to original <select> and call refresh.

In this case, we should target the options to disable using corresponding selectors, disable them using attr() and then call refresh, as shown below:

$(function() {
  $("#speed").selectmenu();
  $("#first").attr("disabled", true); // any other selector as you wish
  $("#speed").selectmenu("refresh");
});
label {
  display: block;
  margin: 30px 0 0 0;
}
select {
  width: 200px;
}
<link href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<label for="speed">Select a speed</label>
<select name="speed" id="speed">
  <option id="first">Slower</option> <!-- disabled by dynamically-->
  <option>Slow</option>
  <option selected="selected">Medium</option>
  <option disabled>Fast</option> <!-- disabled by default-->
  <option>Faster</option>
</select>