Change Input color when typing x characters [duplicate]

0

I would like that when a person types more than 10 characters in my input , he would change the color to green, otherwise it turns red.

That's without the refresh . The person would not have to click the button to change colors. I would like it to change the colors while the person has typed.

    
asked by anonymous 09.08.2018 / 03:55

2 answers

0

Just use input in JavaScript . With it you can detect all changes to the field.

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><inputtype="text" id="message" />
    
09.08.2018 / 04:06
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>
    
09.08.2018 / 04:08