K
K
keche2017-09-12 16:05:39
css
keche, 2017-09-12 16:05:39

How to add a class if the input field is empty (in jQuery)?

How to add class .error to input if it is empty?
There are three fields in total, two input and 1 texarea.
The following code prevents sumbit from submitting data if at least one field is empty. And it highlights the entire form, not individual input or textarea elements.
It is necessary that the erorr class be added to each input or textarea element if they are not filled, when clicking on the button.
Now the code is like this:

$('#form').submit(function() { // проверка на пустоту заполненных полей.
    if (document.form.name.value == '' || document.form.email.value == '' || document.form.usertext.value == '' ) {
      $(this).addClass('error');
      valid = false;
      return valid;
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Petrov, 2017-09-12
@Mirkom63

I recently made a form for myself, your problem is implemented there: https://github.com/lesson-web/forms-lw
In a nutshell, you need to iterate over all inputs and if they are empty, then display an error:

$('form').find('input').each(function(){
  if($(this).val().lenght==0){
    $(this).addClass('error');
  }
});

N
netrox, 2017-09-12
@netrox

https://jqueryvalidation.org/
Not to reinvent the wheel.

A
Ankhena, 2017-09-12
@Ankhena

1. Check length, if 0, then add class, otherwise remove.
http://jquery.page2page.ru/index.php5/Type_string
2. https://webref.ru/css/empty

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question