Martin Bean
Martin Bean

Reputation: 39389

JavaScript click event after confirmation dialog

I have a button that has two click handlers on it:

  1. Show a native JavaScript confirmation dialog to the user to confirm the action.
  2. Set some attributes on a separate form element, and submit that form.

They’re jQuery-based and look like this:

$('[data-confirm]').on('click', function (e) {
  if (! confirm($(this).data('confirm')) {
    e.preventDefault();
    e.stopImmediatePropagation();
  }
});

$('.js-remove-item').on('click', function (e) {
  e.preventDefault();

  console.log('clicked');

  var $form = $('#remove-item-form');

  $form.attr('action', $(this).data('url'));
  $form.submit();
});

The button HTML looks like this:

<button type="button"
        class="btn btn-primary js-remove-item"
        data-confirm="Are you sure you want to remove this item?">

However, the console logs “clicked” as the confirmation dialog is displayed. I only want that event listener fired if the user confirms the action.

How would I go about this?

Upvotes: 1

Views: 1980

Answers (1)

Martin Bean
Martin Bean

Reputation: 39389

Figured out a solution for this.

For the “remove item” logic, instead of attaching the class to the button itself I’ve added it to a parent element. Using bubbling, it means any listeners on the button itself are triggered (the confirmation dialog). If that event propagates, it will do so to its parent, which has the “remove item” class name and logic bound.

Upvotes: 1

Related Questions