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 trialRossella Rosin
15,734 PointsWhat's the benefit of using val() over attr()?
in this case they just seem equivalent - it's possible to obtain exactly the same result with both, and they differ by just a few characters, not really something anyone ought to be concerned about.
Are there are other situations in which val() is preferable and there's no other way to achieve the same result? Or is val() for some reason more performant? Is it just a shortcut for getting and setting the value attribute exclusively?
In other words, why does val() exist? ;-)
1 Answer
Steven Parker
231,275 PointsValue is not an attribute, it's a property. For properties, JQuery provides .prop(), which will return the current value, where .attr() might return only the initial value. So, .val() is not really like .attr("value"), but depending on the element, it might be the same thing as .prop("value").
But for some elements, it's not the same at all. For example, $("select").val()
will return the value of the currently selected option, but $("select").prop("value")
will not. The difference is even greater if you want to set the value.
So the real advantage of .val() is that it adapts to the element type, returning or setting the property that you are most likely to actually want for each type.
Rossella Rosin
15,734 PointsRossella Rosin
15,734 Pointsthank you Steven! your answer is really insightful!