making input fields styled when they contain values Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of making input fields styled when they contain values without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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;}

Answer

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:

We are here to answer your question about making input fields styled when they contain values - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji