Adding ‘Clear Button’ to the Multi-choice Type of Quiz

Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Amrata Ramchandani -
Number of replies: 9

Quiz Scenario

  • Type of question:  Multichoice (only one answer, with the options provided as radio buttons).

  • The question has negative marking for wrong answers

  • A student selects an option. But later change their mind and decide to leave the question unanswered. 

Issue

Currently, the student is not able to clear their answer, and hence is forced to select at least one option.

Related forum discussions / tracker issues

Following are the few discussions on forums and tracker based on deselecting the selected answer in quiz.

  1. https://moodle.org/mod/forum/discuss.php?d=239872

  2. https://moodle.org/mod/forum/discuss.php?d=204748

  3. https://moodle.org/mod/forum/discuss.php?d=156661

  4. https://tracker.moodle.org/browse/MDL-5311

Previously proposed ideas / solutions

Some of the ideas proposed in above forum discussions are :

  1. Adding an extra choice to the given question as "No answer", worth zero points.

  2. Using the multiple answer version as that allows students to check and uncheck the answers.

(With the 2nd solution discussed, unless we specify that there is only one correct answer, it gives a wrong idea to the students that there could be multiple correct answers when the quiz can have requirements of only one correct answer per question. )

The above given solutions are just tweaks to deal with the current scenario, where there is no feature of clearing the selected option.

Proposed solution

The user journey will be as follows :

  1. When setting a multiple choice question, the teacher will have a choice whether or not to include a clear button in the quiz (in a case the teacher chooses to have negative marking), which can be done by checking/unchecking a checkbox provided for the same while setting up the quiz.

  2. A Clear button appears in all the multichoice questions.

  3. When the student answers a multichoice question, and later decides not to answer it, they will now have an option to clear it. This is recorded in the audit trail.

  4. From the evaluator’s perspective, the last state of the answer will be used, irrespective of whether the last attempt was correct or wrong, or unanswered.

Development done till date

Currently, we have developed one outline logic (key steps) to implement only points 2 to 4 above.

  1. We are using javascript to clear the selected radio button.

  2. The clear button is implemented in an ad-hoc manner (through ‘Additional HTML’, the process is shown below), just to show a proof of the concept. Later it will be added by the plugin to the page renderer.

  3. The attempt history is also being updated at every step of question attempt.

To enable the ‘clear’ functionality work on your moodle, do the following :

  1. Write the HTML Part to add the ‘Clear’ button (see below)

  2. Apply the patch (given in the attachment).


Part 1 : Adding ‘Clear Button’ using the ‘Additional HTML’ feature of Moodle

To add the HTML Part i.e., ‘Clear Button’, we are currently using the ‘Additional HTML’ feature available  to the site administrators.

  • The path for the same is :

       Site Administration -> Appearance -> Additional HTML

  • Within Head, add the following link to JQuery :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
  • Before body is closed, add following script to add clear button after options of every question of type ‘Multichoice’ :

<script>
   if ($("input[type]").is(":radio")) {
       $(".answer").append("<button type='button' name='clear' >Clear</button>");
   }
$('button[name=clear]').on('click', function() {
   $(this).closest('.answer').find(':radio').prop('checked', false)
});
if ($('.content').parent().hasClass("deferredfeedback")) {
   if ($(' .answer .r0 input').prop('disabled')) {
       $("button[name=clear]").remove();
   }
} else {
   if (!($('div.im-controls').length)) {
       $("button[name=clear]").remove();
   }
}
</script>


Part 2 : Applying the patch

The patch to be applied is provided as an attachment.

Work to be done

  1. This feature works, as of now, only for the following question behaviours

  • Deferred Feedback
  • Immediate Feedback
  • Interactive with multiple tries

         It will be implemented for other question behaviours later.

  1. Adding the ‘clear’ button HTML code in core moodle code.

  2. Clear Button is still visible after the attempt is over in Immediate Feedback and Interactive with multiple tries that too in some Layouts(e.g Multiple Questions on single page) otherwise it is working fine.We are working on this part and will be implemented soon.

  3. ‘Clear Button’ feature will be made optional, i.e., a checkbox will be provided in Quiz Settings and hence, the teacher will have a choice whether or not to have ‘Clear Button’ in MCQs.


          Please give us your valuable feedback!

Average of ratings: Useful (1)
In reply to Amrata Ramchandani

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Amrata Ramchandani -
Kindly refer the patch attached in this reply,I mistakenly attached different patch file.
In reply to Amrata Ramchandani

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Amrata Ramchandani -

Hi Everyone,

As said above that few things were pending in the clear button functionality like 

1) Adding clear button in core moodle(through separate javascript file)

2) Providing an option to choose whether or not to include a clear button in the quiz(In Quiz Settings->Question Behaviour->Show More Options)

We have worked on the above two functionalities and created a final patch.The patch is tested on latest moodle version i.e. Moodle 3.3+ and works fine.To apply the patch, kindly download the latest moodle version,the final patch attached here and apply the patch before doing the installation as few settings are set only during the installation time as quiz is the core functionality of moodle.

Please let us know if you face any kind of issue in it.



In reply to Amrata Ramchandani

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

I am sorry to say this is a really bad approach to solving this problem.

If you are doing things with JavaScript, then there really should be not need to make any change to any of the core PHP code. (Try adding

<input type="hidden" name="(copy this from one of the radio buttons" value="">

to the HTML instead.)

If anyone applies your patch, they are going to have big problems when the time comes to upgrade their Moodle site to a new version of Moodle.

Average of ratings: Useful (1)
In reply to Tim Hunt

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Emma Richardson -
Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Plugin developers

It would definitely be preferable if this could just be built into core than to have people add a patch but, if you really need the option, at least it gives one.  

If there is a way to just add to additional html, that would be good too.

Average of ratings: Useful (1)
In reply to Emma Richardson

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Amrata Ramchandani -

Hi Ma'am,

Thanks for your inputs.The patch is given here just for the testing purpose and to get inputs from people.

We can approach for the patch to be included in coming moodle versions once it is being reviewed and tested successfully.

Additional HTML can also be done to some extent but few changes in the moodle core were needed to make the clear button an optional thing and to keep as an choice in Quiz Settings,so that users can set if they need this feature or not.So we thought of making a single patch in which all these changes are incorporated.

In reply to Tim Hunt

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Amrata Ramchandani -

Hi Tim,

Thanks for your inputs,we have implemented the clearing functionality according to your suggestions which is discussed below.The patch file was uploaded for the testing purpose and is temporary,once we get enough positive responses from people and if it is successfully reviewed we can approach to get it included in the future release of the moodle.

Coming back to clearing the options with only javascript and not changing the core php code.By implementing the clear functionality using that approach works except that one extra record is added in the mdl_question_attempt_step table with the state todo.

Following is the process which we used  to temporarily reproduce the required thing:

Overview of Quiz:

Quiz had 2 MCQs with negative Marking and each quiz had 3 options.Quiz had the layout of single question on single page.Using Javascript we added the 4th radio button(hidden from user)  with null value and a clear button to each of the questions.

The Quiz was attempted in the following way to test the functionality:

  1. 1st Question was attempted(2nd option selected out of 3 options which are visible to the user) and on clicking the next button the selected answer was processed and stored in DB.
  2. Came back to the 1st question and clicked Clear button,which clears the user selected radio button and 4th option is selected i.e. null value and subsequently the null value is processed and stored in the database.
  3. The Expected value to be stored in DB is Blank/NULL but instead the value which gets stored after processing the data is 0.The reason for it is while processing the data NULL value is being typecasted to int which eventually makes the submitted data as value 0. So Basically on clearing the selected answers ends up selecting the 1st option.Certainly which we are not expecting(This can be fixed by making the NULL get stored in DB as it is w/o typecasting),which we tried and below are the outcomes for the same.
  4. So,now we got the NULL stored in DB by tweaking a line of core php code and the clear button functionality is working as expected,which changes the state of question from complete to todo and answer is stored as NULL.
  5. Then we move backwards towards the 1st question to check if the NULL value is still retained(It is retained).Now when we move forward towards the 2nd question.A new record is added in question_attempt_step table with state as todo(It is basically processing the NULL value twice,which we feel is redundant)The screenshot of the tables(qa_step and qa_step_data) and the audit trail of this attempt is given below.

Records inserted while attempting the 1st question->mdl_question_attempt_step table

mdl_question_attempt_step

Records inserted while attempting the 1st question->mdl_question_attempt_step_data table

  mdl_question_attempt_step_data

Audit trail of an attempted quiz question

Audit trail of attempted quiz question

We have used following JS Code for implementing the above tested functionality

jQuery(function($) {
    var radioButtonName = document.querySelector(".answer .r0 input").getAttribute("name");
    if ($("input[type]").is(":radio")) {
        $(".answer").append("<input type='radio' name=" + radioButtonName + " value='' id=" + radioButtonName + 3 + "><button type='button' name='clear' >Clear</button>");
        document.getElementById(radioButtonName + 3).style.display = 'none';
    }
    $('button[name=clear]').on('click', function() {
        $(this).closest('.answer').find(':radio').prop('checked', false)
        document.getElementById(radioButtonName + 3).checked = true;
    });
    if ($('.content').parent().hasClass("deferredfeedback")) {
        if ($('.answer .r0 input').prop('disabled')) {
            $("button[name=clear]").remove();
        }
    } else {
        if (!($('div.im-controls').length)) {
            $("button[name=clear]").remove();
        }
    }
});   

The attached patch file in previous comments contains the core php changes along with a bit of javascript.There are in all 9 additions in PHP Code,stated below

  1. Strings to add in Quiz Lang File
  2. Code to add “Enable Clear button” option in Quiz Settings
  3. Code to include JS Files if clear button is enabled in quiz settings
  4. Code to include enableclear=0 and enableclear_adv=1 records in config_plugin moodle table
  5. Code to include enableclear attribute in quiz table
  6. Code to check if the submitted data is empty in process_Action function
  7. Code to set the data back to _order in question_attempt_step_data db table when clear button is clicked
  8. Code to get the last answer or _order step name instead of directly passing   answer
  9. Code to call the last step name(out of answer or _order) instead of directly passing answer

The details of above additions(Manual code edit instructions in order to incorporate the above changes) are given in another fresh comment below.

Even if we go with just Javascript to make the clear functionality working,Changes required in core php code can be minimized but can't be completely avoided,as to make

  1. Clear Button as an optional feature(#1 to #5 additions will be required).
  2. A conditional typecasting in order to facilitate processing of quiz answers containing NULL values.

Can you please suggest how this functionality should move forward considering the above outcomes explained?Do you want us to fix the issues in above outcomes or will the previous patch should be used ?


Thanks and Regards,

Amrata



In reply to Amrata Ramchandani

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Ray Sun -

It works !

The script works and no issues with it. (On 3.3).

I realised that this is a essential feature for the site I am planning to build, since it is a MCQ site and this feature is required for quizzes with negative marking.


My general thoughts: 

- An 'Additional HTML' or an 'Independent plug in' (as opposed to a core files edit) would be preferable, since it will not get over-written by any Moodle upgrade.

- But not all features may work with the above approach, so a 'Core code edit' may be the only option for some plug ins.

- In which case, the patch file should work with the current version + the preceding version of Moodle, since many users would not have upgraded to the latest version.

- Version control for the patch file - just to keep track of which release of Moodle was it intended for.


Manual code edit instructions - for those who cannot run patch files and for clarity on what the patch file does:

- Many shared hosting services are not Git enabled and may limit SSH access.

- So any plug-in / add-on should preferably come with manual install instructions.

- It will also help users customize the add-on to their specific needs.


Inclusion of useful plug-ins / add-ons into the core code:

- Since there are options to track the downloads of plug-ins, the popularity and / or the functionality can be used as a criteria for prioritizing inclusion into the core-code of the next Moodle release.


Bottom-line :  Useful feature. Deserves to be included in the core-code of a future release. 

Thank you for building this.




Average of ratings: Useful (1)
In reply to Ray Sun

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Amrata Ramchandani -

Hi Ray,

Thanks for your suggestions.

1) This patch file is for the testing purpose,once we get enough positive responses from people and if it is successfully reviewed we can approach to get it included in the future release of the moodle.Till then we can have version control of the patch file.

2) Additional HTML can be done but to make this functionality as an optional thing we will have to put an option in Quiz Settings,so we had to make changes in core moodle for that.

3) I will put an manual code edit instructions as soon as possible,So that other developers can understand the new code and can customize more according to their specific requirements.

4) Creation of independent plugin is a good idea in order to keep a track of its usefulness to users.I will work on it asap.



In reply to Amrata Ramchandani

Re: Adding ‘Clear Button’ to the Multi-choice Type of Quiz

by Amrata Ramchandani -

Here are the Manual Code Instructions for those who can’t apply the patch to make the clear functionality working completely.


Step 1 through 5 are required to make the clear button feature as an optional,so that one can include or exclude as per their need.


1) Strings to add in Quiz Lang File

moodle/mod/quiz/lang/en/quiz.php -> add the below code in alphabetical order of strings

$string['configenableclearbutton'] = 'If enabled, the clear button will be added in the quiz with multichoice questions in order to support an option to clear selected radio buttons';
$string['enableclearbutton'] = 'Enable clear button for single answer questions';
$string['enableclearbutton_help'] = 'If enabled, the clear button will be added in the quiz with multichoice questions in order to support an option to clear selected radio buttons';

2)Code to add “Enable Clear button” option in Quiz Settings->Question Behaviour

moodle/mod/quiz/mod_form.php ->after each attempts build on block of code 

      $mform->addElement('selectyesno', 'enableclear', get_string('enableclearbutton', 'quiz'));
      $mform->addHelpButton('enableclear', 'enableclearbutton', 'quiz');
      $mform->setAdvanced('enableclear', $quizconfig->enableclear_adv);
      $mform->setDefault('enableclear', $quizconfig->enableclear);


3) Code to include JS Files if clear button is enabled in quiz settings 

moodle/mod/quiz/attempt.php -> after attemptobject is created

/* Check for clear button option and insert corresponding JS(clearbutton.js file is attached here and jquery is already present in moodle just write the correct path to include it here) */
if($attemptobj->get_quiz()->enableclear) {
$PAGE->requires->js( '/lib/jquery/jquery-3.1.0.min.js');
$PAGE->requires->js( '/mod/quiz/clearbutton.js');
}


4)Code to include enableclear=0 and enableclear_adv=1 records in config_plugin moodle table

moodle/mod/quiz/settings.php -> after each attempts build on block of code

// Clear Button for multichoice questions.
$quizsettings->add(new admin_setting_configcheckbox_with_advanced('quiz/enableclear',get_string('enableclearbutton', 'quiz'), get_string('configenableclearbutton', 'quiz'),array('value' => 0, 'adv' => true)));


5)Code to include enableclear attribute in quiz table

moodle/mod/quiz/db/install.xml -> after each attempt builds on block of code

 <FIELD NAME="enableclear" TYPE="int" LENGTH="4" NOTNULL="true" DEFAULT="0" SEQUENCE="false" COMMENT="Whether the clear button should be enabled for multichoice questions"/>

Step 6 through 9 are required to make the clear functionality work properly


6) Code to check if the submitted data is empty ?

moodle/question/engine/questionattempt.php -> in process_action()

/* While clearing the quiz option,we are trying to bring the question attempt step data to '_order' and we could find that '_order' data only in initial step  i.e step[0] */
if( empty($submitteddata)){
        $step_zero_data = $this->steps[0]->get_all_data();
        $pendingstep->set_data($step_zero_data);
      }


7)Code to set the data back to order when clear button is clicked

moodle/question/engine/questionattemptstep.php ->after get_all_data()

// Setting Step Data
   public function set_data($data){
       $this->data = $data;
   }


8)Code to get the last answer or _order step name instead of directly passing answer

moodle/question/engine/questionattempt.php -> after get_last_step()

    public function get_unfinished_step() {
    foreach($this -> get_reverse_step_iterator() as $step) {
    $name = array('answer', '_order');
    foreach($name as $key) {
    if ($step -> has_qt_var($key))
    return $key;
    }
    }
   }


9)Code to call the last step name(out of answer or _order) instead of directly passing answer

 moodle/question/type/multichoice/question.php -> inside get_response()

public function get_response(question_attempt $qa) {
        $laststep_name=$qa->get_unfinished_step();
        return $qa->get_last_qt_var($laststep_name, -1);
     }

Please comment,if anyone gets any issue while doing these changes.