Richard Young Richard Young - 17 days ago 6
jQuery Question

Changing list into dropdown and adding selected option

I have a list of products.

<ul style="padding-left: 0;">
<li style="text-indent: 0;">
<a href="/products/category1/sub-category1.html"><span>Category 1</span></a>
<ul style="padding-left: 0;">
<li style="text-indent: 0;">
<a href="/products/category1/sub-category1.html"><span>Sub Category 1</span></a>
</li>
<li style="text-indent: 0;">
<a href="/products/category1/sub-category2.html"><span>Sub Category 2</span></a>
</li>
</ul>
</li>
<li style="text-indent: 0;">
<a href="/products/category2.html"><span>Category 2</span></a>
<ul style="padding-left: 0;">
<li id="selected_sub_category" style="text-indent: 0;">
<a href="/products/category2/sub-category1.html"><span>Sub Category 1</span></a>
</li>
</ul>
</li>
<li style="text-indent: 0;">
<a href="/products/category3/sub-category1.html"><span>Category 3</span></a>
<ul style="padding-left: 0;">
<li style="text-indent: 0;">
<a href="/products/category3/sub-category1.html"><span>Sub Category 1</span></a>
</li>
<li style="text-indent: 0;">
<a href="/products/category3/sub-category1.html"><span>Sub Category 2</span></a>
</li>
<li style="text-indent: 0;">
<a href="/products/category3/sub-category1.html"><span>Sub Category 3</span></a>
</li>
</ul>
</li>
<li style="text-indent: 0;">
<a href="/products/category4.html"><span>Category 4</span></a>
<ul style="padding-left: 0;">
</ul>
</li>
</ul>


I have some jQuery that can convert the list into a select menu when the screen reaches a certain resolution. Which one to show is controlled by CSS media queries.

// Create the dropdown base
$("<select />").appendTo("nav");

// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Go to..."
}).appendTo("nav select");

// Populate dropdown with menu items
$("nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("nav select");
});


This code has the first option as selected always. What I'd like to do is have the option I'm on as being selected. Is there a way to change that easily. I can't seem to figure it out since I'm new to jQuery.

Answer

It's not about the jQuery. It's a simple logic. You are adding selected="selected" to all the <option> elements:

// Create default option "Go to..."
$("<option />", {
   "selected": "selected",   // Seeee???
   "value"   : "",
   "text"    : "Go to..."
}).appendTo("nav select");

What you need to do is, remove that line and replace it with some flag or the current URL.

// Create default option "Go to..."
$("<option />", {
   "selected": (isCurrentLink) ? "selected" : false,
   "value"   : "",
   "text"    : "Go to..."
}).appendTo("nav select");

You need to define the isCurrentLink to return true based on the current page selected or the menu item related to the current page.