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'); } }); });
if (input.val().length >= 1) {- Igor