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 trialRyan Libed
7,386 PointsAdding 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);
2 Answers
Steven Parker
230,995 PointsSo 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
7,386 PointsTHANK YOU SO MUCH. I can't believe I overlooked that.
I got my code to work =)
Steven Parker
230,995 PointsI 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.
Ryan Libed
7,386 PointsHere is the snapshot of my code
Steven Parker
230,995 PointsThat code quoting string is 3 accents (```), not 3 apostrophes (''').
Ryan Libed
7,386 PointsThank you. On the preview, the form is accessible by clicking on the registration button as a modal on the email input
Ryan Libed
7,386 PointsRyan Libed
7,386 PointsHere is the full snapshot of my code if this helps
https://w.trhou.se/gz5sk8uts8