0

Using JS & HTML markup Always works: Codepen

if (document.forms['myForm'].name.value == '') {
    name.style.background = "pink";
}
else {
    name.style.background = "white";
}

Using JS & CSS Doesn't always work: Codepen

if (document.forms['myForm'].name.value == '') {
    // give this element the .error class from the css file
    name.className = name.className + " error";
}
else {
    // this removes the error class
    name.className = name.className.replace(" error", ""); 
}

Why is JS & CSS inconsistent? I would like to use this approach since I can just apply an error class to each of the elements I want to effect.

1
  • If you want something that will update as the client uses it you can expand on this codepen.io/NewToJs/pen/MYqgOm?editors=001 this will add an event listener to anything with the class of required and listen for the input event. The function required() will need much more work but I thought I would show you this anyway. You can expand on this to display errors for each input before the user submits Commented Mar 5, 2015 at 22:20

1 Answer 1

3

Everytime you hit your submit button and a field isn't filled out, error is added to the classList property; if you submit more than once, multiple classes will be added. Whereas when removing the class, .replace(' error', '') will only replace the first instance of error it comes across.

You can use regex to find all instances of error:

name.className = name.className.replace(/ error/g, "");

Codepen

Sidenote: You can take advantage of classList but its browser support is limited.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't even think that I kept adding the .error class. Beautifully done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.