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

HTML jQuery Basics (2014) Creating a Password Confirmation Form Using next()

Question about the function 'passwordEvent'

My question concerns the second and third time the word "this" is used in the jQuery using .next() example.

function passwordEvent(){
    //Find out if password is valid  
    if($(this).val().length > 8) {
      //Hide hint if valid
      $(this).next().hide();
    } else {
      //else show hint
      $(this).next().show();
    }
}

Why is it that we're using $(this).next to refer to the span tag that is meant to be hidden? Could we not just refer to the span tag directly, and then hide it? Are we just learning doing this to learn about .next()?

2 Answers

Aisha Blake
STAFF
Aisha Blake
Treehouse Guest Teacher

You're using the value being entered into the input field to determine whether or not the span should be hidden. You can't do this without referencing the input element and it's convenient to use .next() to hide or show the span once you have the relevant information. Does that make sense?

It does make sense. My thought was that if I referred to the span tag to show or hide in this fashion:

function passwordEvent(){
    //Find out if password is valid  
    if($(this).val().length > 8) {
      //Hide hint if valid
      $("form span").hide();
    } else {
      //else show hint
      $("form span").show();  // With using "form span"
    }
}

...then it would produce the same result. But that, if I understand this correctly, would show or hide all the span tags. Do I have that right?

Aisha Blake
Aisha Blake
Treehouse Guest Teacher

If I'm understanding correctly, in that case, you wouldn't use .next() because then you'd be selecting the element after the span and not the span itself and there aren't any more sibling elements after the spans. Even then, yes, you'd be selecting (and either showing or hiding) both span elements at once.