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

3

I have this CSS of INPUT , and 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">
    
asked by anonymous 07.08.2018 / 06:52

1 answer

3

Only with CSS you can not. Create a oninput JavaScript event to detect interaction with input and trigger a function.

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

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

In the example below I put it to 3 characters just 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: link

    
07.08.2018 / 07:12