Search code examples
javascripthtmlcssformsstyles

making input fields styled when they contain values


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 &hellip;">
   </div>
   <div>
      <label for="lastName">Last Name:</label><br>
      <input type="text" name="lastName" id="lastName" placeholder="Last name &hellip;">
   </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;}

Solution

  • 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: