I have prepared a jsFiddle for my question:
For that I have taken the jQuery UI menu with categories example and have just added VALUE="some_number"
attribute to each <LI>
-element:
<ul id="menu">
<li class="ui-widget-header"> Category 1 </li>
<li value="1"> Option 1 </li>
<li value="2"> Option 2 </li>
<li value="3"> Option 3 </li>
<li class="ui-widget-header"> Category 2 </li>
<li value="4"> Option 4 </li>
<li value="5"> Option 5 </li>
<li value="6"> Option 6 </li>
</ul>
Then I am trying to retrieve and display that value in an alert on a button click:
$("#menu").menu({
items: '> :not(.ui-widget-header)'
});
$('#btn').button().click(function(ev) {
ev.preventDefault();
var value = $('#menu').val();
// var value = $('#menu li').attr('value');
alert('Selected menu value: ' + value);
});
but the .val()
seems to be a bad choice here, I probably need to go through $("#menu")
for that?
Also I wonder, why are the list items highlighted on hover and on item selection in the jQuery example - but not in my jsFiddle?
UPDATE:
The HTML-select/optgroup/option workaround suggested by clearshot66 is nice, but I would like to get my jQuery UI menu working... I have also posted my problem at the jQuery forum.
Try something similar to this, it'll do what you're looking for a little cleaner
Also note, your hover isn't working because you need to add a hover attribute on your CSS
Example for yours, not mine:
#menu li:hover{background-color:yellow;}
$('#btn').click(function() {
var value = $('#menu').val();
alert('Selected menu value: ' + value);
});
#menu{overflow:auto;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="menu" size='6'>
<optgroup label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
<p><input type="button" id="btn" value="Show Selected" /></p>
Otherwise, for yours, since they're li, you'd need to add the following:
$("#menu li").hasClass("active")
basically finding the li that has the color highlight/class active in this case, then getting the .text() value...In short, a with opt groups would be much more efficient code wise, and can be CSS styled to look like your example as well.