1

I've got a plugin that's got element types. I've got a Transaction element that I need the user to confirm before saving.

I've tried to use the jQuery that comes with craft:

$('form').submit(function(e) {
    var txt;
    if (confirm("Are you sure you want to save?")) {
      txt = "You pressed OK!";
    } else {
      txt = "You pressed Cancel!";
      return false;
      e.preventDefault();
      e.stopPropagation();
      e.stopImmediatePropagation();
    }

    console.log(txt);
  })

but the element still saves on the edit page.

How can I prevent the element from saving if the user clicks cancel.

1 Answer 1

1

The problem is likely that Craft has its attached its own submit handler to the form already, and jQuery event listeners are always triggered in the order they were attached.

You could verify that by doing a $('form').off('submit') (which, in theory, should de-register any existing event listeners for the 'submit' event) - i.e.

$('form').off('submit');
$('form').submit(function(e) {
    ...
});

I don't think de-registering Craft's own event listeners is the best idea, though.

You might have more luck hi-jacking the form's submit button instead of the actual form, i.e. something like this (untested):

$('form').on('button[type="submit"]', 'click', function (e) {
   if (confirm('Are you sure you want to save?')) {
       return true;
   }
   e.preventDefault();
   return false;
});

If that works, you should be almost there – although you'd probably have to hi-jack the form save shortcut as well (i.e. Cmd+S and whatever the Windows equivalent is).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.