Bootstrap Modal before form Submit

前端 未结 5 1501
野性不改
野性不改 2020-12-23 09:52

I\'m new to Modals, I have a Form and when the user clicks submit, It will show a Modal confirming if the user wants to submit, the modal also contains the user input from t

5条回答
  •  别那么骄傲
    2020-12-23 10:05

    I noticed some of the answers were not triggering the HTML5 required attribute (as stuff was being executed on the action of clicking rather than the action of form send, causing to bypass it when the inputs were empty):

    1. Have a
      with some inputs with the required attribute and place a at the end.
    2. A confirmation input where typing "ok" is expected
    3. Add a modal_1_confirm to your html (to confirm the form of sending).
    4. (on modal_1_confirm) add the id modal_1_accept to the accept button.
    5. Add a second modal_2_errMsg to your html (to display form validation errors).
    6. (on modal_2_errMsg) add the id modal_2_accept to the accept button.
    7. (on modal_2_errMsg) add the id m2_Txt to the displayed text holder.
    8. The JS to intercept before the form is sent:

      $("#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. Also some stuff when clicking the Buttons from the modals:

    $("#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");
    });
    

    Important Note: So just be careful if you add an extra way to show the modal, as simply clicking the accept button $("#modal_1_accept") will assume the validation passed and it will add the "ready" attribute:

    • The reasoning for this is that $("#modal_1_confirm").modal("show"); is shown only when it passed the validation, so clicking $("#modal_1_accept") should be unreachable without first getting the form validated.

提交回复
热议问题