Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda