How do I change the color of INPUT when it exceeds a certain number of characters?

Asked

Viewed 50 times

3

I have this CSS of INPUT, and I would like it to change the background color when it exceeds 70 characters.

CSS

.imv-frm-campo{
    width: 95%;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    color: #333;
    margin-bottom: 10px;
    background-color: #D9ECF1;
    border: 0;
}

HTML

<input name="nome_cliente" type="text" class="imv-frm-campo">

1 answer

3


Only with CSS you can’t. Create an event oninput in Javascript to detect interaction in input and trigger a function.

Can specify by name: document.querySelector("[name='nome_cliente']")

Check that more than 70 characters were typed with this.value.length >= 70 with a ternary operator alternating the background color if the value is greater or less than the number of characters.

In the example below I put for 3 characters only to illustrate:

document.querySelector("[name='nome_cliente']").oninput = function(){
   this.style.backgroundColor = this.value.length >= 3 ? "red" : "#D9ECF1";
}
.imv-frm-campo{
    width: 95%;
    font-size: 20px;
    padding: 10px;
    box-sizing: border-box;
    color: #333;
    margin-bottom: 10px;
    background-color: #D9ECF1;
    border: 0;
}
<input name="nome_cliente" type="text" class="imv-frm-campo">

If you want a generic code for several fields with different boundaries: https://jsfiddle.net/kLg8q7dr/

  • Can I specify which INPUT I want to apply? Type by input name.

  • I put it this way <script type="text/javascript">&#xA; document.querySelector("input").oninput = function(){&#xA; this.style.backgroundColor = this.value.length >= 3 ? "red" : "#D9ECF1";&#xA;}&#xA; </script> but it didn’t work.

  • For me since the first example did not work

  • Put the code in: document.addEventListener("DOMContentLoaded", function(){ código aqui });

  • It worked perfectly. Because for me it only worked with the inclusion of this code?

  • The DOMContentLoaded is executed only after the elements have been added to the page.

  • If you want a generic code for several fields: https://jsfiddle.net/kLg8q7dr/

Show 2 more comments

Browser other questions tagged

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