Change Input color when typing x characters

Asked

Viewed 1,000 times

-1

I wish that when a person typed more than 10 characters in my input, he changed the color to green, otherwise it turns red.

That without the refresh. The person would not need to click the button in order to change the colors. I would like you to change the colors while the person was actually typing.

2 answers

1


Just use the event input in the Javascript. With it you can detect all field changes.

Example with Javascript "Pure":

/* Captura o campo */
const fieldMessage = document.querySelector("#message")

/* O evento INPUT irá detectar todas as alterações no valor digitado/colado */
fieldMessage.addEventListener("input", _ => {

  /**
   * Verifica se o valor digitado possui mais de 10 caracteres
   * Caso possua, adiciona a classe `valid`
   */
  if (fieldMessage.value.length > 10) {
    fieldMessage.classList.remove("invalid")
    fieldMessage.classList.add("valid")
  }
  /* Caso contrário remove-a */
  else {
    fieldMessage.classList.remove("valid")
    fieldMessage.classList.add("invalid")
  }
})
input.valid {
  /* Altera a cor da borda */
  border: 2px solid green;
  
  /* Altera a cor da sombra */
  box-shadow: 0 0 5px green;
}

input.invalid {
  /* Altera a cor da borda */
  border: 2px solid red;
  
  /* Altera a cor da sombra */
  box-shadow: 0 0 5px red;
}
<input type="text" id="message" />

Example with jQuery:

/* Captura o campo */
const fieldMessage = document.querySelector("#message")

$("#message").on("keyup", function(){
  if ($("#message").val().length > 10) {
    $(this).addClass("valid").removeClass("invalid")
  } else {
    $(this).addClass("invalid").removeClass("valid")
  }
})
input.valid {
  /* Altera a cor da borda */
  border: 2px solid green;
  
  /* Altera a cor da sombra */
  box-shadow: 0 0 5px green;
}

input.invalid {
  /* Altera a cor da borda */
  border: 2px solid red;
  
  /* Altera a cor da sombra */
  box-shadow: 0 0 5px red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message" />

0

<input type="text" id="ex" onBlur="ts()">
<script>
  function ts(){
 var a = document.getElementById('ex').value;
 var b = a.length;
if(b<10)
    document.getElementById('ex').style.background ="red";
else
    document.getElementById('ex').style.background ="green";

  }  
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.