Script adding multiple submits to form in modal

Asked

Viewed 35 times

2

Next, I am trying to perform a password recovery form on a modal, however, each time I click on the button that opens the modal, a Submit event is added to the form. Any idea how I can solve this problem ?

below the jquery code.

            // --- -------------- Modal Usuário  -- ------------

                $(document).on("click", "#resetarSenha, #novoUsuario", function(){
                    if($(this).attr('id') == "resetarSenha"){
                        $("#tituloModal").text("Redefinir senha");
                        $('form.form_usuario').attr("id","resetSenha");
                        $("#modalUsuarioBody").html('<div class="form-group">'+
                                                    '<label for="matricula"><strong>Matrícula</strong></label>'+
                                                    '<input type="text" class="form-control mascara" name="matricula" required>'+
                                                    '</div>'+
                                                    '<div class="form-group">'+
                                                        '<label for="senha"><strong>Data de nascimento</strong></label>'+
                                                        '<input id="mascara2" type="text" class="form-control" name="nascimento" required>'+
                                                        '<input type="hidden" name="acao" value="validar"'+
                                                    '</div>');
                        $("#resetSenha").on("submit", function(e){
                            e.preventDefault();

                            var dados = $(this).serialize();
                            $.ajax({
                                url: '../analytics/login/Usuario.php',
                                type: 'POST',
                                data: dados,
                                success: function(data) { 
                                e.preventDefault
                                if (data != ""){
                                    $("#modalUsuarioBody").html(data); 
                                }else{
                                    $("#modalUsuarioBody").append('<div class="alert alert-danger naoEncontrado" role="alert">Usuário não encontrado. Por favor, realize o cadastro.</div>');    
                                    setTimeout(function () {  
                                        $(".naoEncontrado").remove(); 
                                    }, 2000);
                                    //alert(data);
                                }
                                }    
                            })
                        })                           


                    }
                    if($(this).attr('id') == "novoUsuario"){

                        $("#tituloModal").text("Novo usuário");
                        $('form.form_usuario').attr("id", "addUsuario");
                        $("#modalUsuarioBody").html('<div class="form-group">'+
                                                        '<label for="nome"><strong>Nome</strong></label>'+
                                                        '<input type="text" class="form-control" name="nome" required>'+
                                                    '</div>'+
                                                    '<div class="form-group">'+
                                                        '<label for="matricula"><strong>Matrícula</strong></label>'+
                                                        '<input type="text" class="form-control mascara" name="matricula" required>'+
                                                    '</div>'+
                                                    '<div class="form-group">'+
                                                        '<label for="senha"><strong>Senha</strong></label>'+
                                                        '<input type="password" class="form-control" name="senha" required>'+
                                                    '</div>'+
                                                    '<div class="form-group">'+
                                                        '<label for="senha"><strong>Data de nascimento</strong></label>'+
                                                        '<input id="mascara2" type="text" class="form-control" name="nascimento" required>'+
                                                        '<input type="hidden" name="acao" value="adicionar"'+
                                                    '</div>'); 

                        $("#addUsuario, #resetSenha").on("submit", function(e) {
                            e.preventDefault();  
                                var dados = $(this).serialize();
                            $.ajax({
                                url: '../analytics/login/Usuario.php',
                                type: 'POST',
                                data: dados,
                                success: function(data) {                       
                                    classe = null;
                                    if(data == 1) {
                                        msg = "Adicionado com sucesso.";
                                        classe = "alert alert-success"
                                    }else{
                                        msg = "Erro ao adicionar. Usuário já cadastrado."
                                        classe = "alert alert-danger";
                                    }
                                    $("#resultado").removeClass();
                                    $("#resultado").addClass(classe);
                                    $("#resultado").show();
                                    $("#resultado").html(msg);
                                    setTimeout(function () {  
                                        $("#resultado").hide();  
                                    }, 2000);
                                    $('#addUsuario').trigger("reset");
                                },
                                error: function(xhr, status, error) {
                                    alert(xhr.responseText);
                                }
                            });
                            return false;
                            });            
                    }
                    mascaraMatricula();
                    mascaraData();            
                })

------------------- html of the buttons that drive the modal ----------------

                 <div class="dropdown-menu" style="padding: 15px; padding-bottom: 10px;">
                    <form id="ajax_auth" action="" class="form-horizontal"  method="" accept-charset="UTF-8">
                        <input class="form-control login mascara" type="text" name="login" placeholder="Matrícula" required/>
                        <input class="form-control login" type="password" name="senha" placeholder="Senha" required/>
                        <input class="btn btn-primary w-100 mb-1" type="submit" name="submit" value="Entrar" />
                        <div id="resultadoAuth" class="mt-2 p-1" role="alert"></div>
                        <div id="resetarSenha" class="form" style="margin:0 auto"><a data-toggle="modal" data-target="#modalUsuario" href="#">Esqueci minha senha</a></div> <!-- Botão que abre o modal -->
                        <div id="novoUsuario" class="form">Novo usuário?   <a data-toggle="modal" data-target="#modalUsuario" href="#">Cadastre-se</a></div>  <!-- O outro botão que abre o mesmo modal -->
                    </form>                                 
                </div>

----------------------- html of modal form ---------------------------

<div class="modal" tabindex="-1" role="dialog" id="modalUsuario"> 
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-center" style="margin: 0 auto"><strong id="tituloModal"></strong></h5>
            </div>
            <form class="form_usuario" action="" method ="" >
                <div id="modalUsuarioBody" class="modal-body"></div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Enviar</button>
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Sair</button>
                </div>
            </form> 
        </div>
    </div>
</div>
  • The button is inside a form? Post HTML tb so we can analyze.

  • Ready! My idea is to make depending on the button the user clicks, appear the information based on the goal of the button by ajax. Thanks in advance.

  • Also put the HTML of the form.

  • I think it’s best to separate the HTML from the JS and put the scripts out of the modal.

  • Done. I put the html of both.

1 answer

0


By including the event submit within the event click you are creating multiple instances each time you open the modal.

In this case you need to do 2 things:

1) Place events submit outside of events click, that is, each thing separate:

$("seletor").on("submit", function(){ ... });
$("seletor").on("click", function(){ ... });

2) Use delegation on selectors. Instead of:

$("#resetSenha").on("submit", function(e){...

Use:

$(document).on("submit", "#resetSenha", function(e){

Do this at every event submit.

  • Thank you so much! You’ve helped so much.

Browser other questions tagged

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