Score:0

Add an event listener to select list

cn flag

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);
Jaypan avatar
de flag
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.
cn flag
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 :-)
Score:0
cn flag

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.

cn flag
I had forgotten that :-) using a class solved the issue.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.