###Just JS
Just JS
###JS + CSS
JS + CSS
###Just JS
###JS + CSS
Just JS
JS + CSS
You can try something like this:
- Create a function that validates a form.
- This function will fetch all mandatory elements
:not(.optional)
. - Each one should have a valid value. If not, return false.
- This function will fetch all mandatory elements
- Pass this validation value to another function that handles UI state.
- Here, if the value is true, enable button and show optional fields
- If false, disable buttons and hide optional fields.
###Just JS
function empty_check() {
var forms = document.getElementsByTagName("form");
for (var i = 0; i < forms.length; i++) {
handleUIState(forms[i], validateForm(forms[i]));
}
}
function validateForm(form) {
var list = form.querySelectorAll('textarea, input:not(.optional)');
var valid = true;
for (var i = 0; i < list.length; i++) {
valid = valid && !!list[i].value;
}
return valid;
}
function handleUIState(form, valid) {
var optional = form.querySelector('.optional');
if (optional) {
optional.style.display = valid ? 'block' : 'none';
}
form.querySelector('button').disabled = !valid
}
<body onload="empty_check()">
<form>
<textarea oninput="empty_check()"></textarea>
<input type="email" oninput="empty_check()">
<button type="submit">Submit</button>
</form>
<form>
<textarea oninput="empty_check()"></textarea>
<input class="optional" type="email" oninput="empty_check()">
<button type="submit">Submit</button>
</form>
<form>
<input type="email" oninput="empty_check()">
<button type="submit">Submit</button>
</form>
... etc ...
</body>
###JS + CSS
function empty_check() {
var forms = document.getElementsByTagName("form");
for (var i = 0; i < forms.length; i++) {
handleUIState(forms[i], validateForm(forms[i]));
}
}
function validateForm(form) {
var list = form.querySelectorAll('textarea, input:not(.optional)');
var valid = true;
for (var i = 0; i < list.length; i++) {
valid = valid && !!list[i].value;
}
return valid;
}
function handleUIState(form, valid) {
form.classList.toggle('valid', valid)
form.querySelector('button').disabled = !valid
}
.valid{}
.optional{
display: none;
}
.valid .optional {
display: block;
}
<body onload="empty_check()">
<form>
<textarea oninput="empty_check()"></textarea>
<input type="email" oninput="empty_check()">
<button type="submit">Submit</button>
</form>
<form>
<textarea oninput="empty_check()"></textarea>
<input class="optional" type="email" oninput="empty_check()">
<button type="submit">Submit</button>
</form>
<form>
<input type="email" oninput="empty_check()">
<button type="submit">Submit</button>
</form>
... etc ...
</body>
default