Issue
I mean when there is an error in the input in the form due to required or empty fields, how can I style the form in that instance. Like this Notice how the form labels and fields are red. How can I do that?
I tried using the form submit event to find out if there are no values in the field but nothing happens. Please help.
function func() {
alert("nice!");
document.getElementById("form").submit();
var day = document.getElementById("day").value;
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var dayLab = document.getElementById("dayLab");
var monLab = document.getElementById("monLab");
var yrLab = document.getElementById("yrLab");
if (day == null || month == null || year == null) {
dayLab.style.color = "rgb(200, 0, 0)";
monLab.style.color = "rgb(200, 0, 0)";
yrLab.style.color = "rgb(200, 0, 0)";
}
}
Solution
Apply the
requiredattribute to appropriate inputs:<input type="text" required>Add a listener on each input for the
invalidevent to add a class containing the styling you want.(optional) If you want inputs to be validated as the user tabs through the form, add a listener on the form for the
focusoutevent, to validate the field which just lost focus. ThecheckValidity()method automatically fires theinvalidevent if validation fails (which adds the class to style the input as invalid), but if validation succeeds you need to remove that class.
Note that if you submit a form programmatically using the submit() method, validation is not performed.
document.querySelectorAll('input[type=text]').forEach(e => {
e.addEventListener("invalid", evt => {
evt.target.classList.add('invalid')
})
})
document.getElementById('f1').addEventListener('focusout', evt => {
if (evt.target.checkValidity())
evt.target.classList.remove('invalid')
})
body, input {
font-family: sans-serif;
font-size: 16px;
}
input {
padding: 3px 8px;
border: 1px solid #eee;
border-radius: 5px;
}
input[type=submit] {
padding: 5px 12px;
}
label {
display: block;
margin-bottom: 1em;
}
.invalid {
border: 1px solid red;
}
label:has(.invalid) {
color: red;
}
<form id="f1">
<label>First Name* <input type="text" required></label>
<label>Last Name* <input type="text" required></label>
<input type="submit">
</form>
Answered By - Brett Donald
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.