Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make select option selected based on an unordered list using jQuery

I've converted my unordered list into a select option list, however I'm not sure how can I make the 'selected' attribute added the option which correlates to the same hyperlink in the list.

Mark-up

<div class="navigation">
    <ul>
         <li><a href="foo.html">Foo</a></li>
         <li><a href="bar.html" class="selected">Bar</a></li>
         <li><a href="boo.html">Boo</a></li>
    </ul>
</div> 

Javascript

$('<select />').appendTo('.navigation');

// Populate dropdown with menu items
$('.navigation ul a').each(function() {
 var el = $(this);
 $('<option />', {
    "value"   : el.attr('href'),
    "text"    : el.text()
 }).appendTo('.navigation select');
});
// Navigate to page on select option
$('.navigation select').change(function() {
  window.location = $(this).find('option:selected').val();
});
// Hide navigation list
$('.navigation ul').hide(); 
like image 686
calebo Avatar asked Dec 19 '12 23:12

calebo


1 Answers

You can use hasClass method:

 $('<option />', {
    "value"      : el.attr('href'),
    "text"       : el.text(),
    "selected"   : el.hasClass('selected')
 }).appendTo('.navigation select');

http://jsfiddle.net/5V5rY/

like image 149
undefined Avatar answered Oct 14 '22 01:10

undefined