Avoid reattaching javascript when a form is rebuilt by ajax callback

by argiepiano   Last Updated December 15, 2017 17:07 PM

I have a form that uses ['#attached']['js'] to attach a simple javascript file. A checkbox element of this same form uses ['#ajax'] to dynamically update some portions of the form. I'm finding that, when the form is rebuilt after the ajax callback, the javascript file is reattached multiple times, causing unintended behaviors.

Is there any way to avoid reattaching a javascript file to a form if that same javascript has been attached previously?

Tags : 7 javascript ajax

Answers 1

As Clive mentioned, the usual way to solve this is to use once() when attaching behaviors:

Drupal.behaviors.myBehavior = {
  attach: function (context, serverSettings) {
    $('elementSelector', context).once('myId', function () {
      // The code that will be executed only once.

Also, check the official docs on Managing JavaScript in Drupal 7.

Kirill Shabunov
Kirill Shabunov
December 15, 2017 16:47 PM

Related Questions

Why would a form suddenly stop updating?

Updated April 14, 2017 14:07 PM

Trigger Drupal Ajax via Javascript

Updated May 17, 2017 13:07 PM

How to edit user profile fields in Drupal 8?

Updated May 30, 2017 14:07 PM

How can we use JS and AJAX in Drupal 7?

Updated January 30, 2018 07:07 AM