0

How does one access a menu selection in jQuery UI? I'm used to forms like the following:

<form>
<select onchange="showUser(this.value)">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>

Accessing the form is then done using:

function showUser(str) {
    if (str=="1"){
      // do something
   }
}

But, the jQuery UI form doesn't seem to have a function attached to it, so I am not sure how to access selections.

Here is the jQuery UI menu code (from http://jqueryui.com/menu/#categories):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Menu - Categories</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    $( "#menu" ).menu({
      items: "> :not(.ui-widget-header)"
    });
  });
  </script>
  <style>
  .ui-menu { width: 200px; }
  .ui-widget-header { padding: 0.2em; }
  </style>
</head>
<body>

<ul id="menu">
  <li class="ui-widget-header">Category 1</li>
  <li>Option 1</li>
  <li>Option 2</li>
  <li>Option 3</li>
  <li class="ui-widget-header">Category 2</li>    
  <li>Option 4</li>
  <li>Option 5</li>
  <li>Option 6</li>
</ul>

How does one access each option like in the previous example?

1 Answer 1

2

This should work.

$('#menu').menu({
    select: function(event, ui) {
        alert(ui.item.text());
    }
});

jQuery UI's menu has a select method where you can access the event and the UI widget. This adds an event listener, whereby you have access to the data.

Sign up to request clarification or add additional context in comments.

2 Comments

Please include an explanation as to why this should work, as the code itself may solve the problem but it is not self-evident to all future viewers of this question.
Thanks, how do I access this later in the code? In my previous example, I use if (str=="1"){ do something }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.