mod/quiz/amd/src/submission_confirmation.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. * A javascript module to handle submission confirmation for quiz.
  17. *
  18. * @module mod_quiz/submission_confirmation
  19. * @copyright 2022 Huong Nguyen <huongnv13@gmail.com>
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. * @since 4.1
  22. */
  23. import {saveCancelPromise} from 'core/notification';
  24. import Prefetch from 'core/prefetch';
  25. import Templates from 'core/templates';
  26. import {get_string as getString} from 'core/str';
  27. const SELECTOR = {
  28. attemptSubmitButton: '.path-mod-quiz .btn-finishattempt button',
  29. attemptSubmitForm: 'form#frm-finishattempt',
  30. };
  31. const TEMPLATES = {
  32. submissionConfirmation: 'mod_quiz/submission_confirmation',
  33. };
  34. /**
  35. * Register events for attempt submit button.
  36. * @param {int} unAnsweredQuestions Total number of un-answered questions
  37. */
  38. const registerEventListeners = (unAnsweredQuestions) => {
  39. const submitAction = document.querySelector(SELECTOR.attemptSubmitButton);
  40. if (submitAction) {
  41. submitAction.addEventListener('click', async(e) => {
  42. e.preventDefault();
  43. try {
  44. await saveCancelPromise(
  45. getString('submission_confirmation', 'quiz'),
  46. Templates.render(TEMPLATES.submissionConfirmation, {
  47. hasunanswered: unAnsweredQuestions > 0,
  48. totalunanswered: unAnsweredQuestions
  49. }),
  50. getString('submitallandfinish', 'quiz')
  51. );
  52. // Save pressed.
  53. submitAction.closest(SELECTOR.attemptSubmitForm).submit();
  54. } catch {
  55. // Cancel pressed.
  56. return;
  57. }
  58. });
  59. }
  60. };
  61. /**
  62. * Initialises.
  63. * @param {int} unAnsweredQuestions Total number of unanswered questions
  64. */
  65. export const init = (unAnsweredQuestions) => {
  66. Prefetch.prefetchStrings('core', ['submit']);
  67. Prefetch.prefetchStrings('core_admin', ['confirmation']);
  68. Prefetch.prefetchStrings('quiz', ['submitallandfinish', 'submission_confirmation']);
  69. Prefetch.prefetchTemplate(TEMPLATES.submissionConfirmation);
  70. registerEventListeners(unAnsweredQuestions);
  71. };