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 1

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

Did I get this correctly?

I just want to make sure that I understand everything that's happening in this video:

var $select = $("<select></select>");// we create a detached element, respectively an //element menu;
$("#menu").append($select); // we append select to the div menu;

// Cicle over menu links - pretty self explanatory;
$("#menu a").each(function() {

var $anchor = $(this);// this variable has the value of the link we clicked on;

 var $option = $("<option></option>"); //this variable is each option in the select menu and it will have a different value depending on the link we clicked;

 $option.text($anchor.text());// we set the text of the option to be the text of the clicked anchor;

 $option.val($anchor.attr("href")); //we take the value of option and set it to the href of
// the link we clicked on;

// append option to select
$select.append($option);// we append the option to the select menu;
});

Question:

  • how $option.val() knows to replace the href attribute? Can an element have more thann one value? Thank you!

2 Answers

Steven Parker
Steven Parker
230,274 Points

:point_right: $option.val() does not replace the href attribute.

When given an argument, it replaces the value attribute. In this code it is replacing it with the href attribute from the anchor (a) element.

And an element can have only one value attribute.

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

So .val() can only replace the value attribute? In this case it replaces what? When we created the "option" detached element we didn't give it any value. Are we talking about this kind of value?

<input type="checkbox" value="1">Is this the value we're talking about?</input>

Other than this, did I get the other steps right?

maybe you`ll understand it better this way

/*you could also do it with 'attr()' method instead of using the 'val()' method*/
$option.attr('value', $anchor.attr('href')); //this sets the option value attribute with the anchor href

and you`re

<input type="checkbox" value="1">Is this the value we're talking about?</input>

the value attribute will get change from 1 to whatever you type on the val() method