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

Lawrence Lee
Lawrence Lee
4,240 Points

jQuery project 3 questions

Hey guys,

So on this particular project, it seems really straight forward until I see the section where Andrew explains how the option's value changes to the select's value.

For example, on the code challenge ask me to making sure the window.location is set to the $select's value.

Here is the code before:

//Create a select and append to #menu
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 button 
var $button = $("<button>Go</button>");
$("#menu").append($button);
//Bind click to button
$button.click(function(){
  //Go to select's location
  window.location = $select;
});

Then here is the code after:

//Create a select and append to #menu
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 button 
var $button = $("<button>Go</button>");
$("#menu").append($button);
//Bind click to button
$button.click(function(){
  //Go to select's location
  window.location = $select.val();
});

I do understand using the val attribute part, but I just don't understand why he set the location of window from option to select...

Can anyone explain this?

1 Answer

Hossam Khalifa
Hossam Khalifa
17,200 Points

You can use both.The select.val() will automatically get you the Window location but the problem with the option is that you have to specify wich option should be used and this is more difficult to do. So it is a lot easier to use the select and the value of the selected option would be used for window.location