Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
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;}
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

I cant add a comment so, I see that your css selector missing a dot to define a class. If that is not the problem let me know.

EDIT:

Ok the problem is you are using AddClass() as a function but it is a jQuery function. You need to use .classList.add("form-required") method instead. And same with the removeClass method. Instead you should use .classList.remove("form-required")

And dont forget to call your function after the function definition. Like this:

borderColour();

Final Advise

But you need an event listener instead of calling your function once on page load. So you need to add this function to maybe a keypress event on the inputs.

Sample Code

HTML

<form id="theForm" 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>

CSS

.form-required {border: 2px solid red !important;}

Javascript(Pure Vanilla)

// Border colour for input web forms
function borderColour() {

// You could use below comment to select all inputs but you will probably need to select a textarea too. So selection is a next step. 
//var inputs = document.querySelectorAll('input');
var firstNameSelector = document.getElementById('firstName');
var value = firstNameSelector.value;
  console.log(firstNameSelector.value);
  if(value == '') {
       firstNameSelector.classList.add("form-required");
     }
  else {
   firstNameSelector.classList.remove("form-required");
       }

}
//Adding an event listener to the form element. If you click outside the form you will get the class toggle if the input is empty it will get the red border an so on...
document.getElementById("theForm").addEventListener("focusout", borderColour);

You can add the event listener to all the input elements but to do that you will need a loop(maybe a foreach) like in the other answers.

about 4 years ago · Santiago Trujillo Denunciar

0

Here is a working snippet

// Border colour for input web forms
function borderColour(e) {
  if(e.target.value == '') {
     e.target.setAttribute("class", "form-required");
  } else {
     e.target.removeAttribute("class");
  }
}

var inputs = document.querySelectorAll('input');

inputs.forEach(function(el){
  el.onpropertychange = borderColour;
  el.oninput = borderColour;
});
.form-required {border: 2px solid red !important;}
<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>

about 4 years ago · Santiago Trujillo Denunciar

0

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:

  • :not().
  • :placeholder-shown.
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda