group/amd/src/grouppicker.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * @module core_group/groupPicker
  17. * @copyright 2022 Matthew Hilton <matthewhilton@catalyst-au.net>
  18. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  19. */
  20. /**
  21. * Class used for interfacing with the group select picker.
  22. *
  23. * @class core_group/GroupPicker
  24. */
  25. export default class GroupPicker {
  26. /**
  27. * Creates the group picker class and finds the corresponding DOM element.
  28. *
  29. * @param {String} elementId The DOM element id of the <select> input
  30. * @throws Error if the element was not found.
  31. */
  32. constructor(elementId = "groups") {
  33. const pickerDomElement = document.getElementById(elementId);
  34. if (!pickerDomElement) {
  35. throw new Error("Groups picker was not found.");
  36. }
  37. this.element = pickerDomElement;
  38. }
  39. /**
  40. * Returns the DOM element this class is linked to.
  41. *
  42. * @returns {HTMLElement} The DOM element
  43. */
  44. getDomElement() {
  45. return this.element;
  46. }
  47. /**
  48. * Returns the selected group values.
  49. *
  50. * @returns {Number[]} The group IDs that are currently selected.
  51. */
  52. getSelectedValues() {
  53. const selectedOptionElements = Array.from(this.element.querySelectorAll("option:checked"));
  54. const selectedGroups = selectedOptionElements.map(el => parseInt(el.value));
  55. return selectedGroups;
  56. }
  57. }