Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Why use .val() instead of .attr("value")?
Why use .val() instead of .attr("value")? Is there a difference other than .val being shorter and simpler?
There is actually quite a big difference between
.attr("value"). The former gets the objects desired value (from the HTML code) whereas the latter gets the objects actual value once the HTML document is created.
For example, you could have an object and give it an
X value, but then later in your code change its' value to
.attr("value") would return
X here (because that's what you set the attribute to) whereas the
.val() would return
Y (because that's what it ended up with).
Hope that helps.
Marcio Mello7,861 Points
The example was a "getter" one. What about the setter (like in the video)?
The code was written as:
I did some experimentation and re-wrote that line as:
The result was the same. is there any sistuation where these two codes would result in different outcomes?