I am wondering if it's possible to set an element "required" based on some other element state. For instance, say I have an input element that I want to be "required" if and only if the user checks a specific checkbox. First, is this possible to do it without the use of JavaScript? Second, if we use JavaScript, of course one could set up a rule / validation if the user checks that checkbox, but what about consistency regarding the default browser validation errors? Would it be "correct" to add the "required" attribute to the element once the checkbox is clicked? I don't see an alternative here. What are your thoughts on this one?
Using HTML5, we can create a form with built in validation (i.e. no javascript required). Earlier, we were using JAVASCRIPT to control form validation. These form controls are meant for both Desktop, tablets and smart phones.
To ignore HTML validation, you can remove the attribute on button click using JavaScript. Uer removeAttribute() to remove an attribute from each of the matched elements.
The value must be greater than or equal to the value. There must be a value (if set). Unless the step is set to the any literal, the value must be min + an integral multiple of the step. The number of characters (code points) must not be less than the value of the attribute, if non-empty.
There are three categories of HTML5 form validation features: HTML attributes on <input> , <select> , and <textarea> elements. (From here on out, I will just refer to them all as <input> cause brevity) CSS pseudo selectors.
I don't think you can do this without javascript.
With javascript, you could do this easily enough.
I would add the required
attribute only after the checkbox is clicked.
In fact, I would make this a toggled
piece, so that the user can uncheck and unrequire the input.
However, I would not rely on browser's implementation of the required
attribute. Instead, I would create my own required notification using some CSS (highlighting, animation, displaying some words).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With