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 trialAshkan Entezari
3,956 PointsCan we use .attr() instead of .prop()?
Hello everyone,
I'm a bit confused here! Is it possible to set the "selected" property of <option> using .attr()? Apparently we can't but what is the difference of these two?
2 Answers
Rafael Capati
10,725 PointsFrom the JQuery documentation:
To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.
Attributes vs. Properties
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
Simple example:
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
$(document).ready(function() {
// All of this will work
$("select option[value=2]").prop("selected", "selected");
// $("select option[value=2]").prop("selected", true);
// $("select option[value=2]").attr("selected", "selected");
});
Hariidaran Tamilmaran
iOS Development Techdegree Student 19,305 PointsActually, you can use .attr() for the 'selected' attribute. You just do:
$("yourSelectOption").attr("selected", true).