Home > database >  How to pause a <form> submisson, do some work, and then continue with the submission
How to pause a <form> submisson, do some work, and then continue with the submission

Time:05-22

I have to pass a form to a route, but before that I want to use a modal to request confirmation from the user. I am using preventDefault() to stop the submission and handle the confirmation, but now I need to continue with the normal form submission:

<script type="text/javascript">
  $(".btn-close").click((x) => {
    x.preventDefault();
    var text = $(this).val();
    $("#modal_body").html(text);

    $("#removeConfirm").click(() => {
      //$(this).submit();
      //I need to continue with the form submission here
      console.log("Confirmed!");
    });
  });

</script> 

"text" is a value I am passing to the modal;

"#removeConfirm" is the confirmation button in the modal;

I tried "$(this).submit()" but it's not working, any ideas?

CodePudding user response:

preventDefault() isn't going to stop your form from submitting.

It's likely going to be easier to have the submit handler trigger from the modal itself, since you can't really have the data hang in limbo like you're proposing (unless you write the values to some higher order store of course).

CodePudding user response:

$(this).submit() is not working because "this" is the button $(".btn-close") and not the form.

For the form, instead of using a submit button, use a button with a Javascript function and manage there the submission, something like:

<label>Name</label>
<input type="text" name="name" value="" />
<br/>
<label>Phone</label>
<input type="text" name="phone" value="" />
<br/>

<a id="processBtn"  href="javascript:;" >Process</a>
<script>
    $('#processBtn').click(function(e){
        e.preventDefault();
        if (doStuff()) {
            console.log("there we go!");
            $("#waitform").submit();
        }

    });
    function doStuff()
    {
        console.log("i'm sending the form in a sec");
        return true;
        //you can also add a condition and return false if you don't want to submit the form
    }
</script>
  • Related