Paul R
Paul R

Reputation: 2797

Off doesn't work properly

I'm trying to show confirm dialog before form submit:

  $('body').on('submit', 'form[data-confirm-dialog-text]', (e) ->
    form = $(this)
    e.preventDefault()
      $.show_dialog(form.data('confirm-dialog-title'), form.data('confirm-dialog-text'), form.data('ok-text'), form.data('cancel-text'), (->
        form.off('submit').submit()
      ))
  )

On success I do the following: form.off('submit').submit(), but keep getting confirm dialog, which means that form is not inbound.

If I change $('body').on('submit', 'form[data-confirm-dialog-text]' to $('form[data-confirm-dialog-text]').on('submit',everything works fine. What is the difference and what am I doing wrong?

Upvotes: 2

Views: 127

Answers (2)

sergdenisov
sergdenisov

Reputation: 8572

From jQuery's .off() documentation:

The .off() method removes event handlers that were attached with .on(). Calling .off() with no arguments removes all handlers attached to the elements. Specific event handlers can be removed on elements by providing combinations of event names, namespaces, selectors, or handler function names. When multiple filtering arguments are given, all of the arguments provided must match for the event handler to be removed.

It means you should use the same arguments to .off() as to .on. So, try to change:

form.off('submit').submit();

To:

$('body').off('submit', 'form[data-confirm-dialog-text]');
form.submit();

Upvotes: 1

Muthu Kumaran
Muthu Kumaran

Reputation: 17910

The event is bind to body and you should use remove the event from body. So change,

form.off('submit').submit()

to

$('body').off('submit', 'form[data-confirm-dialog-text]');
form.submit();

Upvotes: 1

Related Questions