How do I make the mandatory fields in my input form have a red border when the page is loaded and they are empty, and how to set them back-to-normal styling when they have data inside?
I have this code:
Page:
<form method="post" action="xxx.php" enctype="multipart/form-data" value="multipart/form-data" onload="borderColour()">
<div>
<label for="firstName">First Name:</label><br>
<input type="text" name="firstName" id="firstName" placeholder="First name …">
</div>
<div>
<label for="lastName">Last Name:</label><br>
<input type="text" name="lastName" id="lastName" placeholder="Last name …">
</div>
</form>
Javascript:
// Border colour for input web forms
function borderColour() {
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var firstNameId = document.getElementById('firstName');
var lastNameId = document.getElementById('lastName');
if (firstName == '') {
firstNameId.addClass("form-required");
} else {
firstNameId.removeClass("form-required");
}
if (lastName == '') {
lastNameId.addClass("form-required");
} else {
lastNameId.removeClass("form-required");
}
}
CSS:
.form-required {border: 2px solid red !important;}
I'd suggest using CSS rather than JavaScript:
input,
input:placeholder-shown {
/* default <input> styles */
border: 1px solid red;
}
input:not(:placeholder-shown) {
/* has a value entered */
border-color: gray;
}
References: