0

Есть форма:

<form class="rf" method="post" action="">
            <input type="text" id="login" placeholder="введите логин" />
            <input type="password" id="password" placeholder="введите пароль" />
            <input type="button"  value="Войти" id="button_enter">
</form>

Как с помощью jquery при нажатии на кнопку «Войти» проверить заполняемость текстовых инпутов и если значение какого-либо инпута пустое – данному инпуту присвоить класс error.

2 ответа 2

1

$('.rf').on('click', '#button_enter', function(){
    $('.rf input:not([type=button])').removeClass('error'); 
    let hasErrors = false;

    $('.rf input:not([type=button])').each(function(){
        if ($(this).val().trim() == '') {
          hasErrors = true;
          $(this).addClass('error');    
        }
    });  
    
    return hasErrors ? false : true; // тут отправка формы либо вернуть false
});
.error {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="rf" method="post" action="">
  <input type="text" id="login" placeholder="введите логин" />
  <input type="password" id="password" placeholder="введите пароль" />
  <input type="button" value="Войти" id="button_enter">
</form>

0

const form = document.querySelector('.rf');
const el = [].slice.call(form.elements);

document.getElementById('button_enter').addEventListener('click', () => {
  el.forEach(item => {
    if (!item.value) {
      item.classList.add('error')
    }
  });
})
.error {
  border: 1px solid red;
}
<form class="rf" method="post" action="">
  <input type="text" id="login" mplaceholder="введите логин" />
  <input type="password" id="password" placeholder="введите пароль" />
  <input type="button" value="Войти" id="button_enter">
</form>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.