Creating a Q&A dynamic length form with javascript

Post Reply
darknkreepy3#
Site Admin
Posts: 254
Joined: Tue Oct 27, 2009 9:33 pm

Creating a Q&A dynamic length form with javascript

Post by darknkreepy3# »

So, if you want TRUE or FALSE and or Multiple choice questions with a variety of answer lengths per question that can be tricky, especially for output scripts like PHP and easier with Javascript added. Here is a combination to help you get the idea on just how to dynamically change DIV ID contents innerHTML and use things like radio and onClick to bring it to life. Feel free to use and modify this, just don't sell it as is. Be kind.

Code: Select all

<?php
	/*
	add_question.php v1.0 by Kristoffe Brodeur. ©2015 All Rights Reserved.
	07-26-2015
	*/
	//
	$n=10;
	$def=4;
	$nStr="<div class='newQ_area'>NUMBER OF QUESTIONS</div>";
	//
	for($a=0;$a<$n;$a++)
		{
		$selected="";
		$b=$a+1;
		//
		if($b==$def)
			{
			//$selected="checked";
			}
		$nStr.="<input type='radio' name='qN' value='$b' $selected onClick='buildQuestions($b);'> $b ";
		}
	$nStr.="</div><div id='mArea'></div>";
?>

<form name="add_question" method="POST" action="save_question.php">
	<div class='newQ_area'>
		QUESTION TEXT<br />
		<textarea name="qText" rows="4" cols="80"></textarea><hr />
		TYPE OF QUESTION<hr />
		<input type="radio" name="qT" value="mc" onClick='qMultipleChoice();'> Multiple Choice <input type="radio" name="qT" value="tf" onClick='qTF();'> TRUE | FALSE<br />
		<hr />
		<div id="qArea"></div>
</form>

<script>
	var qArea=document.getElementById('qArea');
	//
	function qMultipleChoice()
		{
		qArea.innerHTML="<?php echo $nStr;?>";
		}
	//
	function qTF()
		{
		qArea.innerHTML="<div class='newQ_area'>TRUE | FALSE</div><input type='radio' name='qN' value='1'> True <input type='radio' name='qN' value='0'> False";
		}
	//
	function buildQuestions(sAmt)
		{
		var mArea=document.getElementById('mArea');
		mArea.innerHTML="POSSIBLE ANSWERS<br />";
		//
		for(a=0;a<sAmt;a++)
			{
			mArea.innerHTML+="<div class='mAns'>"+(a+1)+"<input value='' name='mAnsArr["+a+"]'></div>";	
			}
		}
</script>
Post Reply