I have a HTML form with several inputs which have the required
attribute and thus are automatically validated when the form is submitted. This works fine, but I also have an input field of type='checkbox'
that needs to be invisible/hidden due to special CSS styling, which changes a label
's appeareance to display a styled checkbox. But this checkbox input field also needs to be validated (it has the required
attribute).
So when the form is submitted, the browser (Chrome here) can't focus the invisible field, so it does nothing in the UI and gives the error
An invalid form control with name='consent' is not focusable.
How can I override the form validation to focus the label element instead of the invisible input
element when it is invalid? Are there any useful form validation events that I can hook into to change this behavior?
Thanks in advance.
Edit: It's a bit similar to OPs question and this answer here: https://stackoverflow.com/a/23215333/15717315
Edit 2: I can optionally use jQuery.
This is what it looks like currently:
<div>
<input type='checkbox' id='myfield' class='my-styled-checkbox' name='myfield' required>
<label for='myfield'>
The label
</label>
</div>
Edit 3:
Alright, so I added an event listener to the submit
event of the form. This successfully prevents the from from being submitted when the checkbox isn't checked.
document.getElementById("myform").addEventListener("submit", function(e) {
var field = document.getElementById("myfield");
if (field.checked) {
field.setCustomValidity("");
e.returnValue = true;
}
else {
field.setCustomValidity("Invalid");
e.returnValue = false;
}
});
But it still throws the same error as in the OP, and the validation message does not display.