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 3

My question about method prop()

var $select = $("<select></select>");
$("#menu").append($select);

$("#menu a").each(function(){
var $anchor = $(this);
var $option = $("<option></option>");

if ($anchor.parent().hasClass("selected") ){
$option.prop("selected",true);

}   


$option.val($anchor.attr("href"));    

$option.text($anchor.text());
$select.append($option);
});

var $button = $("<button>Go</button>");
$("#menu").append($button);
$button.click(function(){


window.location = $select.val();    

});

Why here in the part code stated value true? $option.prop("selected",true);

Greg Kaleka
Greg Kaleka
39,021 Points

By the way, I edited your post to add in code formatting. Take a look at how to do this yourself: click on the edit button below your post and click edit. You'll see the markup I added.

2 Answers

Greg Kaleka
Greg Kaleka
39,021 Points

Hi Iliya,

I'm not sure I completely understand your question, but you can find the documentation for the prop() method, and this specific version of it here. Essentially, you're setting the property "selected" to true. If you put false in there, it would remove the property "selected" from the html.

Here's the javascript and resultant html:

script.js
$option.prop("selected", true);

leads to:

main.html
<option selected></option>

whereas:

script.js
$option.prop("selected", false);

leads to:

main.html
<option></option>

Let me know if this answers your question!

-Greg

But if remove value true, code will be work also .

thank you very much for your help!

Niclas Valentiner
Niclas Valentiner
8,947 Points

$option.prop("selected",true); This sets the selected property of $option to true.

why he is set?

Ryan Field
Ryan Field
Courses Plus Student 21,242 Points

It is being set because that is how you make a certain option selected in a dropdown (or select menu). If you are unaware of how such menus work, there is more information here.

Ryan Field thank you! Now i all understood!