0

I've attached the following js to an exposed views form field and it works on first page load but when the form is changed (by ajax) it doesn't fire.

I can't quite work out where to add an event listener for onchange of the select list.

The following doesn't use jQuery but uses the core once library so I would like to avoid jQuery.

/**
 * @file
 * Landing page adjustments.
 */

 (function (Drupal, once) {
    'use strict';
  
    /**
     * Attached behavior for Custom DataLayer.
     *
     * @type {{attach: Drupal.behaviors.CurrentSelectOption.attach}}
     */
    Drupal.behaviors.CurrentSelectOption = {
      attach: function attach(context) {
        // First page load
        let elements = once('CurrentSelectOption', 'select#edit-field-event-country.form-select', context);
        elements.forEach(processingCallback);
      }
    };
  
    function processingCallback(value, index) {
      let option = value.options[value.selectedIndex]
      value.remove (option);
      value.add (option, 0);
    }

})(Drupal, once);
2
  • Why are you avoiding jQuery? It comes bundled with core. It's been almost 2 decades since I wrote raw JS without jQuery, so it's hard for me to provide the solution, though I'd have one without that requirement.
    – Jaypan
    Commented Jun 3, 2022 at 14:52
  • I didn't want to add another dependency to the script if I didn't have to and it was working apart from not being triggered when the form was changed. I've got nothing against jQuery :-) Commented Jun 4, 2022 at 16:17

1 Answer 1

0

When an AJAX call is made through the Drupal API, behaviours are re-attached. So if the API is in use, the answer is simply to put the code inside the attach method in your behavior, where you already have it.

The twist is: don’t use IDs to target elements. This is a general best practice rule for CSS/JS DOM selection, but especially important here, as Drupal will generate a new ID for the form element it replaces. If you inspect the select and its wrapper after the AJAX call, you’ll see -2 appended to the original ID.

Other than that (without a test) your code looks fine.

1
  • I had forgotten that :-) using a class solved the issue. Commented Jun 4, 2022 at 16:12

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.