2
Hello,
With the function below, I validated required fields.
In this case, I don’t use this function to submit the form, but rather to add items to the object.
However, I want to focus on the first mandatory 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;
}
thanks for the feedback, but if I keep
$(campos[i])
will always focus on the last mandatory element and if I change to$(campos[0])
will focus only on the first field, and if I fill the first field, the focus does not move to the second required field.– Wagner Fillio
Better, it was missing the false Return, now it worked. However the class
error focused
only applied to the field with focus, would be able to apply in all mandatory fields and keep the focus on the first unfilled Camo ?– Wagner Fillio
I changed the answer.
– Sam
It worked great, thanks @Sam..
– Wagner Fillio