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.

JavaScript

Ryan Libed
Ryan Libed
7,386 Points

Adding class with jQuery successfully, but once the class is added I cannot remove the class.

Hello,

I created a small challenge for myself to add and remove a class of "has-danger" to a form that I have created with bootstrap.

I have successfully added the class "has-danger" with jQuery through events tested through a conditional statement, but once the the length of the value of input is more more than 8, the class is not dynamically removing itself. I've tried for hours and I can't figure this simple thing out. Code is posted below.

Thank you in advance!

var $mail = $('#email');

function mailLength() { return $mail.val().length < 8; }

function mailValidate() { if (mailLength()) { $mail.addClass("has-danger"); } else { $mail.removeClass("has-danger"); }

}

$mail.focus(mailValidate).keyup(mailValidate);

Ryan Libed
Ryan Libed
7,386 Points

Here is the full snapshot of my code if this helps

https://w.trhou.se/gz5sk8uts8

2 Answers

Steven Parker
Steven Parker
215,972 Points

So when I guessed at the HTML, I assumed the element with the ID of "email" was an input, and the code worked fine.

But now that I see the snapshot, it turns out it's a fieldset; and since the value of the fieldset always has length 0, the class is never removed.

Ryan Libed
Ryan Libed
7,386 Points

THANK YOU SO MUCH. I can't believe I overlooked that.

I got my code to work =)

Steven Parker
Steven Parker
215,972 Points

I guessed at the HTML and CSS code, but when I combined them with the script shown it seemed to work very well. As soon as I type the 8th character, the class changes. And if I backspace to get the length below 8 it comes back.

Perhaps it would help if you share the rest of the code. If you're using workspaces, you can share all the code at once if you make a snapshot of your workspace and post the link to it here.

Steven Parker
Steven Parker
215,972 Points

That code quoting string is 3 accents (```), not 3 apostrophes (''').

Ryan Libed
Ryan Libed
7,386 Points

Thank you. On the preview, the form is accessible by clicking on the registration button as a modal on the email input