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

CSS jQuery Basics (2014) Creating a Password Confirmation Form Perfect

Andrew Chen
Andrew Chen
9,446 Points

Why use .val() when comparing two variables?

Hi, I'm curious as to why we have to use .val() the variable when comparing the variables.

function arePasswordsMatching() {
  return $password.val() === $confirmPassword.val();
}

I understand that we are comparing both strings to check if they are the same but why won't the following code work?

function arePasswordsMatching() {
  return $password === $confirmPassword;
}

Would really appreciate if someone could explain this. Thanks! :)

Andrew Robinson
Andrew Robinson
16,372 Points

http://api.jquery.com/val/

Take a look, using the .val() compares the values of these elements, the second code block you have compares the elements directly, you want to compare what's inside those elements, if that makes sense.

1 Answer

Zhihao Wang
Zhihao Wang
9,687 Points

Hi Andrew,

the variable $password is not storing the actual password that the user has inputted, but rather the actual input field with the #password id. In other words, $password is storing the physical html input element. In jQuery, in order to access what the user has typed in for the password input, we have to grab the value of the password input field, using the val() function.

I hope that has clarified why we use .val() when we want to access the characters that the users have typed in.

Cheers.

Andrew Chen
Andrew Chen
9,446 Points

Hi Zhihao, thanks for the explanation! :)