Check fields when giving Ubmit and if error return to field

Asked

Viewed 1,694 times

3

I have a very long form and would like to click on Ubmit and the field is in error, that the page can scroll (jQuery) to this field so that the person knows exactly what is wrong. I started out that way:

$("#sdEmpresa").removeClass("hidden").css("border", "1px dashed red");

So I was able to speed this up:

if(empresa == ""){

        // callback method use this space how you like
        var body = $("html, body");
        body.animate({scrollTop:0}, 1500, function(){
            $("#sdEmpresa").removeClass("hidden").css("border", "1px dashed red");  
        });

}

Here he goes back to his body, like back to #sdEmpresa?

  • don’t need to use body.animate, just give Focus in the field. It will be difficult to give a more complete answer because each field has a rule... Ever thought of using some plugin for validation?

  • I even thought @Papacharlie but my validations are very specific, but could you put this modified code so that the scroll goes over the field? Learning jQuery (rsrsr)

  • Generally plugins have a vast rule of validation... I recommend taking a look at at least. I didn’t get the end of the comment, you want me to give an example of Focus?

  • If you can, I’d be grateful to see how that code could work the way I seek.

  • Use $('#sdEmpresa').focus();

2 answers

2

Assuming you want to go to the element #sdEmpresa

if(empresa == ""){
    $('html, body').animate({
       scrollTop: $("#sdEmpresa").offset().top
    }, 1500);  
}

But I think you should think of a way to optimize this validation, using a plugin, or go through all <inputs> of the page at once, instead of going testing one by one as you showed in the example:if(empresa == "").

2


Below is a small example: jsfiddle

jquery:

$("form").submit(function (event) {
    event.preventDefault();
    var erro = false;
    var elemento;

    // limpar marcação de erro da tentativa anterior:
    $('form div').removeClass('erro');
    $('.msg-erro').remove();

    // percorrer todos os input e verificar se estão em branco ou não
    $(this).find('input:not(.nao-obrigatorio)').each(function () {
        if ($(this).val() == '') {
            erro = true;
            elemento = $(this);
            return false;
        }
    });

    // aqui pode adicionar outras verificações especificas como combos ou checkbox.
    // definir erro = true e elemento = ao elemento causador do erro.

    if (erro == true) {
        elemento.parent('div').addClass('erro').append((elemento.data('erro') ? '<span class="msg-erro">'+elemento.data('erro')+'</span>' : ''));
        $('html, body').animate({ scrollTop: elemento.offset().top - 100 }, 500);
    } else {
        // não tem nenhum erro, fazer os procedimentos de envio
        alert('Formulario enviado!');
    }
});

HTML:

<form>
    <div>
        <label for="name">* Nome</label>
        <input type="text" id="nome" data-erro="Preencha seu nome">
    </div>
    <div>
        <label for="name">* E-mail</label>
        <input type="text" id="email" data-erro="Preencha seu e-mail">
    </div>
    <div>
        <label for="name">Telefone</label>
        <input type="text" id="telefone" class="nao-obrigatorio">
    </div>
    <div>
        <label for="name">Celular</label>
        <input type="text" id="email" class="nao-obrigatorio">
    </div>
    <div>
        <label for="name">* Endereco</label>
        <input type="text" id="endereco">
    </div>
    <div>
        <label for="name">* Cidade</label>
        <input type="text" id="cidade">
    </div>
    <div>
        <label for="name">* Estado</label>
        <input type="text" id="estado">
    </div>
    <div>
        <label for="name">* Pais</label>
        <input type="text" id="Pais">
    </div>
    <input type="submit" value="Submit">
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.