1

Drupal 8.7.x

For one of my content types I have an entity reference field referencing a taxonomy vocabulary. I have a lot of terms in this vocabulary which makes it tedious to check all the checkboxes if you practically need all of them checked. I would like to integrate a single checkbox at the top of the field in the node creation form that allows you to check/uncheck all the terms at once.

I found a few modules that do this in drupal 7 but so far I had no luck finding anything related to drupal 8.

How would I go about integrating this functionality myself ?

At the moment I have a jquery function in my theme that adds a checkbox at the top of the fields like so:

(function ($, Drupal) {

  /**
   * Check all checkboxes.
   */
  Drupal.behaviors.initFootnotes = {

    attach: function (context, settings) {

      $(".form-checkboxes").prepend($('<input type="checkbox" class="form-checkbox shield-select-all" /><label class="option shield-select-all-label"> Select / Deselect all </label>'));

      let selector = $(".shield-select-all");
      selector.on('click', function (event) {

        console.log("the checkbox is clicked");
        let $options = $('.form-type-checkbox');

        $(".form-checkboxes").closest().find($options).each(
        console.log("I'm an option"),

        $(this).find("input[type=checkbox]").click(),

        )
      })
    }
  };
})(jQuery, Drupal);

The select all checkbox is added but the checkboxes aren't changing their state when the select all checkbox is checked. I noly get "I'm an option" once in the console.

Thanks in advance, Geordi

2 Answers 2

1

Ended up resolving this issue with the following code:

(function ($, Drupal) {

  /**
   * Check/Uncheck all checkboxes.
   */
  Drupal.behaviors.selectAll = {
    attach: function (context, settings) {
      $(".form-checkboxes").prepend($('<input type="checkbox" class="form-checkbox shield-select-all"/><label class="option shield-select-all-label"> Select / Deselect all </label>'));
      $(".shield-select-all").on('click', function () {
        let $isChecked = (!$(this).attr('checked'));
        $(this).parent().find('.form-type-checkbox input[type=checkbox]').attr('checked', $isChecked);
        $(this).attr('checked', $isChecked)
      })
    }
  };

})(jQuery, Drupal);
0

The contributed module checkboxesjs will do this for you out of the box.

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.