Changing the maxlength of short answer questions.

Changing the maxlength of short answer questions.

by James . -
Number of replies: 3

I had a teacher ask me if they could change the length of a short answer question, I had a look at the documentation and couldn't see any way to so I tried testing it out and looked at the page source and found that there was a maxLength attribute on the input field. 

I was able to change the maxLength with this script tag added in the question.

<script type="text/javascript">// <![CDATA[

window.onload = function(){

document.getElementById("id_answer").maxLength = 3;

}

// ]]></script>


After providing this answer to the teacher I found out they actually wanted to increase the length of the question so we ended up using a different script.

<script type="text/javascript">// <![CDATA[

window.onload = function(){

var element = document.getElementById( "id_answer" );

var parent = element.parentNode;

parent.removeChild( element );

parent.innerHTML = '<textarea name="answer" id="id_answer" maxlength="400" cols=50 rows=5></textarea>';

element = null;

}

// ]]></script>



This has worked but I was interested in finding out if there is a different or better way of doing this?

Average of ratings: -
In reply to James .

Re: Changing the maxlength of short answer questions.

by Joseph Rézeau -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers Picture of Translators

Hi James,

I do not understand your problem. Are we talking about the core "short answer" question that can be created in the moodle Question Bank and used in a Quiz activity? or maybe the same type of question but in the Lesson activity?

You write "...I found out they actually wanted to increase the length of the question..."

Do you mean "the length of the question text"? But there is no limit to that text.

I am really perplex.mixed

In reply to James .

Re: Changing the maxlength of short answer questions.

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

The documentation page Short-Answer question type does not explain how to do this, but you can.

In the question text, where you want the answer input box, where you want the answer to appear, type a line of _ characters. for example:

Complete the first line of this Christmas carol:

Good King __________________ looked out, on the feast of Stephen,

The input box will be sized to match the length of the ____s (approximately).

(Update: actually, this is in the docs, but very hard to see.)

In reply to Tim Hunt

Re: Changing the maxlength of short answer questions.

by Jean-Michel Védrine -

Yep and if I remember well I have added the exact same feature to the lesson short answer question smile

EDIT: was added to lesson in  MDL-48473 December 2014, and documented.