user3262713
user3262713

Reputation: 379

jQuery UI selectmenu - how to append option to optgroup

I've figured out how to append options to a select box dynamically - but the additions are appended to the end and not included in an optgroup.

How can I accomplish that? Here is the code that currently just appends to the selectmenu:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <script>
  $(function() {
    roles = $("#roles").selectmenu();
    roles.append("<option value='"+'test!'+"'>" + 'test!' + "</option>");
    roles.selectmenu();
    // let's say I wanted to append to the optgroup labeled 'Your roles' instead. How?
  });
  </script>
</head>
<body>
    <div id="role-select" style="margin-left:30px; margin-top:-10px; float:left;">
      <form action="#">
        <fieldset>
          <label for="roles">Select a role to edit</label>
          <select name="roles" id="roles">
            <optgroup label="Your roles">
              <option value="empty">random 1</option>
              <option value="noreason">2</option>
            </optgroup>
            <optgroup label="Default roles">
              <option value="vvv">3</option>
              <option value="somsdfsdfile">4</option>
            </optgroup>
          </select>
        </fieldset>
      </form>
    </div>
</body>
</html>

Upvotes: 0

Views: 1726

Answers (1)

tmn
tmn

Reputation: 96

You need to select the opgroup you want to append it to. For example:

var roles = $("#roles");
roles.find('optgroup[label="Your roles"]').append("<option value='"+'test!'+"'>" + 'test!' + "</option>");

Upvotes: 1

Related Questions