Bootstrap Modal antes de Enviar el formulario


Soy nuevo en Modales, tengo un Formulario y cuando el usuario hace clic en enviar, mostrará un Modal confirmando si el usuario desea enviar, el modal también contiene la entrada del usuario desde los campos del formulario. Busqué por todo el Internet, pero no puedo encontrar el adecuado para mis necesidades. Y todo lo que veo es que etiquetan el evento de clic para abrir modal en un enlace. tengo un tipo de entrada enviar. ¿Puedes dar ejemplos o ideas? ¡Gracias! Aquí está mi formulario de muestra.

<form role="form" id="formfield" action="inc/Controller/OperatorController.php" method="post"  enctype="multipart/form-data" onsubmit="return validateForm();">
<input type="hidden" name="action" value="add_form" /> 

       <div class="form-group">
         <label>Last Name</label><span class="label label-danger">*required</span>
         <input class="form-control" placeholder="Enter Last Name" name="lastname" id="lastname">
       </div>

        <div class="form-group">
          <label>First Name</label><span class="label label-danger">*required</span>
          <input class="form-control" placeholder="Enter First Name" name="firstname" id="firstname">
       </div>

  <input type="submit" name="btn" value="Submit" id="submitBtn" class="btn btn-default" data-confirm="Are you sure you want to delete?"/>
  <input type="button" name="btn" value="Reset" onclick="window.location='fillup.php'" class="btn btn-default" data-modal-type="confirm"/>
</form>
Author: jgillich, 2014-05-21

4 answers

Así que si lo hago bien, al hacer clic en un botón, desea abrir un modal que enumera los valores ingresados por los usuarios seguido de enviarlo.

Para esto, primero cambia tu input type="submit" a input type="button" y agrega data-toggle="modal" data-target="#confirm-submit" para que el modal se active cuando hagas clic en él:

<input type="button" name="btn" value="Submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" class="btn btn-default" />

A continuación, el diálogo modal:

<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                Confirm Submit
            </div>
            <div class="modal-body">
                Are you sure you want to submit the following details?

                <!-- We display the details entered by the user here -->
                <table class="table">
                    <tr>
                        <th>Last Name</th>
                        <td id="lname"></td>
                    </tr>
                    <tr>
                        <th>First Name</th>
                        <td id="fname"></td>
                    </tr>
                </table>

            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a href="#" id="submit" class="btn btn-success success">Submit</a>
            </div>
        </div>
    </div>
</div>

Por último, un poco de jQuery:

$('#submitBtn').click(function() {
     /* when the button in the form, display the entered values in the modal */
     $('#lname').text($('#lastname').val());
     $('#fname').text($('#firstname').val());
});

$('#submit').click(function(){
     /* when the submit button in the modal is clicked, submit the form */
    alert('submitting');
    $('#formfield').submit();
});

No ha especificado lo que hace la función validateForm(), pero en base a esto debe restringir su formulario de ser presentado. O puede ejecutar esa función en el botón del formulario #submitBtn haga clic y luego cargue el modal después de que se hayan verificado las validaciones.

DEMO

 44
Author: I Can Has Kittenz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-17 13:08:37
$('form button[type="submit"]').on('click', function () {
   $(this).parents('form').submit();
});
 0
Author: Abdo-Host,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-05 12:36:24

Noté que algunas de las respuestas no estaban activando el atributo HTML5 required (ya que las cosas se estaban ejecutando en la acción de haciendo clic en en lugar de la acción de form send, causando que se omitiera cuando las entradas estaban vacías):{[18]]}

  1. Tiene un <form id='xform'></form> con algunas entradas con el atributo requerido y coloca un <input type='submit'> al final.
  2. Una entrada de confirmación donde se espera escribir "ok" <input type='text' name='xconf' value='' required>
  3. Agregue un modal_1_confirm a su html (para confirmar la forma de envío).
  4. (en modal_1_confirm) agregue el id modal_1_accept al botón aceptar.
  5. Agregue un segundo modal_2_errMsg a su html (para mostrar errores de validación de formularios).
  6. (en modal_2_errMsg) agregue el id modal_2_accept al botón aceptar.
  7. (en modal_2_errMsg) agregue el id m2_Txt al soporte de texto mostrado.
  8. La JS para interceptar antes de que se envíe el formulario:

    $("#xform").submit(function(e){
        var msg, conf, preventSend;
    
        if($("#xform").attr("data-send")!=="ready"){
            msg="Error."; //default error msg
            preventSend=false;
    
            conf=$("[name='xconf']").val().toLowerCase().replace(/^"|"$/g, "");
    
            if(conf===""){
                msg="The field is empty.";
                preventSend=true;
            }else if(conf!=="ok"){
                msg="You didn't write \"ok\" correctly.";
                preventSend=true;
            }
    
            if(preventSend){ //validation failed, show the error
                $("#m2_Txt").html(msg); //displayed text on modal_2_errMsg
                $("#modal_2_errMsg").modal("show");
            }else{ //validation passed, now let's confirm the action
                $("#modal_1_confirm").modal("show");
            }
    
            e.preventDefault();
            return false;
        }
    });
    

`9. También algunas cosas al hacer clic en los botones de los modales:

$("#modal_1_accept").click(function(){
    $("#modal_1_confirm").modal("hide");
    $("#xform").attr("data-send", "ready").submit();
});

$("#modal_2_accept").click(function(){
    $("#modal_2_errMsg").modal("hide");
});

Nota importante: Así que tenga cuidado si agrega una forma adicional de mostrar el modal, ya que simplemente haciendo clic en el botón aceptar $("#modal_1_accept") asumirá la validación pasada y agregará el atributo "ready":

  • El razonamiento para esto es que $("#modal_1_confirm").modal("show"); se muestra solo cuando pasó la validación, por lo que hacer clic en $("#modal_1_accept") debe ser inalcanzable sin antes validar el formulario.
 0
Author: ajax333221,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-05 17:29:56

Es fácil de resolver, solo crea un envío oculto:

<button id="submitCadastro" type="button">ENVIAR</button>
<input type="submit" id="submitCadastroHidden" style="display: none;" >

Con jQuery haces clic en enviar:

$("#submitCadastro").click(function(){
    if($("#checkDocumentos").prop("checked") == false){
        //alert("Aceite os termos e condições primeiro!.");
        $("#modalERROR").modal("show");
    }else{
        //$("#formCadastro").submit();
        $("#submitCadastroHidden").click();                     
    }
});
 -1
Author: Pedro Lucas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-01 12:07:49