0

I have a custom form, and I just want a button in the form that fires a jQuery plugin that generates a csv file for download. The problem I'm having is that it seems to fire multiple times for some reason, and I haven't been able to figure out why. I've tried both a button and a link, but I keep getting the same result.

Here's the form button:

$form['export_csv_button'] = array(
  '#type' => 'button',
  '#value' => t('Export to CSV'),
);

And here's my jQuery behavior:

(function ($) {
  Drupal.behaviors.ons_line_item_export = {
    attach: function (context) {
      $("#edit-export-csv-button").click(function() {
        $("#ons-line-item").tableExport({ type: "csv" });
        return false;
      })
    }
  };
})(jQuery);

Is there something obvious I'm missing that is making this happen?

Thanks.

1 Answer 1

2

Try this:

(function ($) {
  Drupal.behaviors.ons_line_item_export = {
    attach: function (context) {
      $("#edit-export-csv-button").once().click(function() {
        $("#ons-line-item").tableExport({ type: "csv" });
        return false;
      })
    }
  };
})(jQuery);

I added the jQuery.once() method.

1
  • Thank you, thank you, thank you. After reading the d.o. issue that added that method, it made sense.
    – wonder95
    Mar 5, 2016 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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