candlejack
candlejack

Reputation: 1209

How to force submit - Asynchronous code in submit event

I'm trying to force submitting of my form, the problem is that I use bootboxjs (that uses an asynchronous code) to make a confirmation dialog before submitting, this is exactly I want, also the required inputs are validated in that way.

This is the structure of my JS code:

$("#myForm").submit(function(e){
  bootbox.confirm({
    message: "Are you sure?",
    buttons: {
        confirm: {
            label: 'Yes',
            className: 'btn-danger'
        },
        cancel: {
            label: 'NO, STOP!',
            className: 'btn-primary'
        }
    },
    callback: function (result){
      if (result)
      {
        // Some code to set values to hidden inputs and another irrelevant stuff...
        // The right command (that I didn't know) to force the form
      }
    }
  });
  return false;
});

How can I avoid this issue and preserve the validation of required inputs?

Upvotes: 1

Views: 366

Answers (1)

charlietfl
charlietfl

Reputation: 171669

You can prevent the jquery event and use a native one to force a browser default submit when you are ready

$("#myForm").submit(function(e){
  // store reference to form due to callback context
  var form = this;

  bootbox.confirm({
    message: "Are you sure?",
    buttons: {... },
    callback: function (result){
      if (result)
      {
        // Some code to set values to hidden inputs and another irrelevant stuff...
        // Now use native submit

         form.submit();
      }
    }
  });
  // prevents jQuery submit only
  return false;
});

Upvotes: 1

Related Questions