Please do not attempt this if you do not fully understand web forms and web form validation with javascript.
Put this in your header with your form validation functions so these variables are created every time the page loads:
function getRandom_0to10(){
var seed = Math.random();
//Multiply to create number 0.0-9.99, then round to integer
return seed = Math.ceil(seed * 10);
}
var x = getRandom_0to10(); // this is "x"
var y = getRandom_0to10(); // this is "y"
var answer = x + y; // this is what they add up to
<p>Please add these two numbers:
<script type="text/javascript">
document.write(x + " + " + y +" = ");
</script>
<input name="arithmetic" type="text" class="add"
id="arithmetic" value="" size="4" maxlength="2" />
</p>
Which displays as (with actual random numbers replacing the "x" and "y"):
Please add these two numbers: x + y =
Call validation from your onsubmit action on your form:
<form id="survey" name="survey" method="post"
onsubmit="return validateForm(this,answer)"
action="/cgi-bin/form-mail/~webclass/raneym3/forms/form.cfg"/>
Add this to your validation function:
function validateForm(whichform,sumanswer){
var errmsg = "Please check your answer on the addition problem.";
for (var i=0; i<whichform.elements.length; i++) {
var element = whichform.elements[i];
... //other validation here
//validate arithmetic
if (element.className.indexOf("add") != -1){
if(element.value != sumanswer){
alert (errmsg);
return false;
}
}
}//end for
return true;
} //end function
An improvement to this method would be to write the warning directly in the page rather than raising an alert box. However this method is simpler to describe generically.