Good day. The bottom line is that if the number of characters in the input exceeds one, then the input class is assigned .valid. But the script for some reason does not work. I enter the characters in the input, and the class is not assigned.

$(function() { input = $('#contact-form input'); if(input.text().length >= 1) { input.addClass('valid'); } else { input.removeClass('valid'); } }); 
  • one
    if (input.val().length >= 1) { - Igor
  • @Igor Maybe you didn’t notice, but they don’t subscribe to the event anywhere :)) - Vasily Barbashev

1 answer 1

Your problem is that you did not subscribe to the field change event. So your code will work only 1 time during initialization.

On pure JS:

 var input = document.getElementById('input'); input.addEventListener('input', function () { if(this.value.length >= 1) { this.classList.add('valid'); } else { this.classList.remove('valid'); } }); 
 input { border: 1px solid red; outline: none; } .valid { border: 1px solid green; } 
 <input type="text" id="input" /> 

Using jQuery (js code only):

 $(function() { var input = $('#input'); input.on('input', function () { // тут можно использовать this, как элемент DOM модели, а не jQuery объект, и использовать не input, а this, НО будет как в примере на чистом js if(input.val().length >= 1) { input.addClass('valid'); } else { input.removeClass('valid'); } }); });