I’ve written a basic form validation script, and now I’m trying to reset the errors that occur if a user doesn’t fill in a required field.
For checkboxes and radio buttons, I’ve added the class error to their labels. The HTML code for this looks like this:
<input class="required" id="Example31" name="Example3" type="checkbox" />
<label for="Example31" class="error">Example Input 3 Option 1</label>
<input class="required" id="Example32" name="Example3" type="checkbox" />
<label for="Example32" class="error">Example Input 3 Option 2</label>
<input class="required" id="Example4" name="Example4" type="radio" />
<label for="Example4" class="error">Example Input 4</label>
To add the errors, I figure out if the any checkbox with the same name is checked, using this script:
$("input.required").each(function() {
// check checkboxes and radio buttons
if ($(this).is(":checkbox") || $(this).is(":radio")) {
var inputName = $(this).attr("name");
if (!$("input[name=" + inputName + "]").is(":checked")) {
var inputId = $(this).attr("id");
$("label[for=" + inputId + "]").addClass("error");
error = true;
};
};
// end checkboxes and radio buttons
});
How can I remove the errors without having to modify the HTML? I’m drawing a complete blank. Here’s what I’m thinking:
- Figure out the name associated with each label that has an error
- Find the checkbox or radio button that has that ID
- Figure out the checkbox or radio buttons name
- Find the rest of the checkboxes or radio buttons with the same name
- Find those inputs IDs
- Find labels with those names
- Clear the errors off of those labels
I’m a t loss, though. If anyone can help, that’d be greatly appreciated.
I was able to solve it myself using this: