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
Abe Layee
8,378 PointsJs form validation not outputting error message
Hello there. I am trying this basic form validation using the setAttribute() method. The first step is hiding the span element when the page is loaded. If the input is empty, I use the setAttribute() to change the display to visible. I am also using the keyup event with addeventlistener. I am trying to be good at raw JavaScript rather than using Jquery. Please tell me on how I can improve this code futher and thank you. No error is outputting in the console log
<p>
<label for="fullName">Full Name</label>
<input type="text" name="first-name" placeholder="John David" id="fullName" onkeyup="formValidation()">
<span class="error" id="fullnameError">Name is required</span>
</p>
css code
#fullNameError {
visibility:hidden;
}
JavaScript code
function formValidation() {
var Name = document.getElementById('fullName').value;
var errorName = document.getElementById('fullnameError');
if (Name==="") {
errorName.setAttribute('style','visibility:visible');
errorName.setAttribute('style','color:red');
} else {
errorName = "";
}
}
addEventListener('keyup',formValidation,false);
2 Answers
Samuel Custer
2,683 PointsPlease view http://codepen.io/anon/pen/JYRrYz
You made a few issues:
- You used the wrong casing in your CSS
- When you write "errorName.setAttribute('style','color:red');" it replaces "errorName.setAttribute('style','visibility:visible');" which means the hidden state will be inherited from your CSS.
You can fix this by writing them in the same line "errorName.setAttribute('style','visibility:visible; color:red');"
Also this isn't wrong, but they way you have it set up it will only show if the user enters something. and then gets ride of it. I would suggest changing the css to visible and making the text red the user backspaces and black if the user has valid input.
Regards, Samuel https://samcus.co
Abe Layee
8,378 PointsThank you now the span element is showing once the user leaves the input element but the else statement is not clearing the fill