1

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.

  • 1
    You obviously cannot have required on the hidden checkbox, so you will have to code your way out of this. You can set the form validity to false if the styled checkbox is not checked – mplungjan Aug 30 '21 at 13:55
  • See my "Edit 3" please. – itspecialist_1 Aug 30 '21 at 14:36
  • As mplungjan already noted, hidden input fields do not participate in validation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/hidden#validation – Simon Aug 25 '22 at 08:07

1 Answers1

0

It would be helpful if you provided with a code example. Also to know if you are using any framework or library like react, angular, etc.

Css properties like

visibility: hidden;

or

display: none;

do not prevent you from editting the DOM with js code. So you should be able to change the field value before submitting.

Also, if the field is not editable by the user, you could just not make it into a required field and assign it a default value. That way you are certain it will never submit being empty.

Looks like you are trying to focus the field, this is not what you want, you should be trying to just change the field's value with js or jquery.

RamaProg
  • 1,106
  • 7
  • 15