Dar submit in form with empty field validations



  • I have this code that validates a form if you have empty fields or you have it submits the form:

    $("#btnAdd").click(function (e) {
    
    e.preventDefault();
    
    var erros = 0;
    
    $("#formAdd input").each(function () {
    
        $(this).val() == "" ? erros++ : "";
    
    });
    $("#formAdd textarea").each(function () {
    
        $(this).val() == "" ? erros++ : "";
    
    });
    
    if (erros > 0) {
    
        $("#msg").show().fadeIn(500).delay(1500).fadeOut(600);
    
    } else {
        $(this).submit(function () {
            var form = $(this);
            var dados = new FormData($(this)[0]);
            $("#btnAdd").prop("disabled", true);
            $.ajax({
                url: 'u/add',
                cache: false,
                contentType: false,
                processData: false,
                data: dados,
                type: 'post'
            }).done(function (data) {
                fetchUser();
                alert("Dados Salvos com Sucesso");
                console.log("STATUS : ", data);
                $("#btnAdd").prop("disabled", false);
                $('#modalAddfoto').modal('hide');
                $('.addfoto')[0].reset();
            }).fail(function (jqXHR, textStatus) {
                console.log("Request failed: " + textStatus);
                $("#btnAdd").prop("disabled", false);
            });
            return false;
    
        });
    }
    

    });

    it valid normal but is not entering that part of the code:
    $(this).submit(function () { ... }

    Detail, if I take the validation and do $('#formAdd').submit(function () { ... } works normally.



  • You can link the submit event directly to the form, and you can pass this as a parameter (already by referencing the Angular).

    <form onsubmit="qualquerEvento(this)">
        <button type="submit">Enviar dados</ button>
    </ form>
    

    <script>
    qualquerEvento(e) { // 'e' agora será o form

        // evitando o comportamento padrão
        e.preventDefault();
    
        // faz as validações dos campos
    
        // faz o ajax para o servidor
    }
    

    </ script>

    It is worth remembering that HTML 5 does not allow certain types of input to be sent with null values, and can further facilitate code writing at validation time.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2