lib/form/amd/src/defaultcustom.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. * Functionality for the form element defaultcustom
  17. *
  18. * @module core_form/defaultcustom
  19. * @copyright 2017 Marina Glancy
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. * @since 3.3
  22. */
  23. define(['jquery'], function($) {
  24. var onChangeSelect = function(event) {
  25. var element = $(event.target),
  26. defaultvalue = JSON.parse(element.attr('data-defaultvalue')),
  27. customvalue = JSON.parse(element.attr('data-customvalue')),
  28. type = element.attr('data-type'),
  29. form = element.closest('form'),
  30. elementName = element.attr('name').replace(/\[customize\]$/, '[value]'),
  31. newvalue = element.prop('checked') ? customvalue : defaultvalue;
  32. if (type === 'text') {
  33. form.find('[name="' + elementName + '"]').val(newvalue);
  34. } else if (type === 'date_selector') {
  35. form.find('[name="' + elementName + '[day]"]').val(newvalue.day);
  36. form.find('[name="' + elementName + '[month]"]').val(newvalue.month);
  37. form.find('[name="' + elementName + '[year]"]').val(newvalue.year);
  38. } else if (type === 'date_time_selector') {
  39. form.find('[name="' + elementName + '[day]"]').val(newvalue.day);
  40. form.find('[name="' + elementName + '[month]"]').val(newvalue.month);
  41. form.find('[name="' + elementName + '[year]"]').val(newvalue.year);
  42. form.find('[name="' + elementName + '[hour]"]').val(newvalue.hour);
  43. form.find('[name="' + elementName + '[minute]"]').val(newvalue.minute);
  44. }
  45. };
  46. var selector = 'input[data-defaultcustom=true]';
  47. $('body').on('change', selector, onChangeSelect);
  48. });