Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Mobile Drop Down Menu Perform: Part 2

Further explanation on .val() and the magic it holds

First off my code works fine and functions how it's supposed to, but I'm having trouble wrapping my head around why it works.

var $select = $("<select></select>");
$("#menu").append($select);
//Cycle over menu links
$("#menu a").each(function() {
  var $anchor = $(this);
   //Create an option
  var $option = $("<option></option>");
  //Option's value is the href
  $option.val($anchor.attr("href"));
   //option's text is the text of link
  $option.text($anchor.text());
  //append option to select
  $select.append($option);
});

//Create a button 
var $button = $("<button>Go</button>");
$("#menu").append($button);

$button.click(function() {
  window.location = $select.val();
});

I understand everything we're doing up until window.location = $select.val(); The value attributes information are inside of the select tag on the options tags, there is no value attribute being added to the select tag. How does this simple three line function know the selected option's attribute when we're referencing the selected tag itself?

1 Answer

Jacob Miller
Jacob Miller
12,466 Points

Using .val() on a select will return the currently selected option's value. So in this case, it's returning the href of the currently selected page in the dropdown, and setting window.location to that href redirects to that page.

God, I was really over thinking this. Thanks man.