Focus on the first validation element - jQuery

2

Hello,

With the function below, I validate required fields.

In this case, I do not use this function to submit the form, but rather to add items to the object.

However, I want to focus on the first required element.

Something like: $('#elemento')[0].focus .

Can you help me?

campos = ['#txt-cep', '#txt-logradouro', '#txt-bairro', '#txt-cidade', '#txt-uf'];

if (campo_obrigatorio(campos)) {
    //faça algo
}

function campo_obrigatorio(campos) {
    var ret = true;
    for (i = 0; i < campos.length; i++) {
        var $form_line = $(campos[i]).parent();
        if (!$(campos[i]).val()) {		
            if (!$form_line.hasClass('error focused')) {
                $form_line.addClass('error focused');
    		//$form_line.find($(campos[i]).focus());
             }
             ret = false;
        }
        else {
            if ($form_line.hasClass('error focused')) {
                $form_line.removeClass('error focused');
            }
        }
    }
    return ret;
}
    
asked by anonymous 04.12.2018 / 13:26

1 answer

1

The error is in this line:

$form_line.find($(campos[i]).focus());

The .focus() must be outside the parentheses of .find :

$form_line.find($(campos[i])).focus();

However, the way you are doing will not select the first, but always the last one.

In this case, select the first element by the classes after the for loop is completed:

$(".error.focused:eq(0) input").focus();

Example:

campos = ['#txt-cep', '#txt-logradouro', '#txt-bairro'];

if (campo_obrigatorio(campos)) {
    //faça algo
}

function campo_obrigatorio(campos) {
    var ret = true;
    for (i = 0; i < campos.length; i++) {
        var $form_line = $(campos[i]).parent();
        if (!$(campos[i]).val()) {
            if (!$form_line.hasClass('error focused')) {
                $form_line.addClass('error focused');
             }
             ret = false;
        }
        else {
            if ($form_line.hasClass('error focused')) {
                $form_line.removeClass('error focused');
            }
        }
    }
    
    $(".error.focused:eq(0) input").focus();
    
    return ret;
}
.error.focused{
   background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><form><p><inputtype="text" id="txt-cep" value="texto">
   </p>
   <p>
      <input type="text" id="txt-logradouro">
   </p>
   <p>
      <input type="text" id="txt-bairro">
   </p>
</form>
    
04.12.2018 / 13:43