nicky77
08-08-2007, 02:59 PM
Hi, I'm trying to implement a randomise function for question numbers in a test generator i'm developing. I've picked up a script which I've modified, however, i'm fairly new to javascript and i don't think i've set it up properly. I have a dynamic array of text fields which contain each question number. I want to use onclick to call the randomiser to reorder the questions while making sure they are all unique. I've placed the code in the <head> section, but i get the error that "div has no properties" - even though i am accessing the same <div> for another piece of js validation. Any help would be greatly appreciated.
<script type="text/javascript">
<!-- Begin
/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Barry Pranklin :: http://www.pranklin.com */
var Found=false
var div = document.getElementById("preview");
var fields = div.getElementsByTagName("input");
var len = fields.length;
var num = len -1;
var Current = new Array();
var MaxValue=len;
var NumUnique=len ;
var Count=0;
var Current = new Array(NumUnique);
GetUnique();
alert("The unique numbers are: " + Current[0] + ", " + Current[1] + ", and " + Current[2])
function GetUnique()
{
for (i=0;Count<NumUnique;Count++)
{
Found=false
var rndValue = get_random()
var j=0
for (j=0;j<Current.length;j++)
{
if (Current[j] == rndValue)
{
Found=true
break
}
}
if (Found)
{
Count--
} else {
Current[Count]=rndValue
}
}
}
function get_random()
{
var ranNum= Math.round(Math.random()*MaxValue);
return ranNum;
}
// End -->
</script>
calling it here....this may be problem but not sure how to resolve it
<input name="Randomise" value="Randomise question order" onclick="GetUnique(this)" type="submit" title="Submit" />
<script type="text/javascript">
<!-- Begin
/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Barry Pranklin :: http://www.pranklin.com */
var Found=false
var div = document.getElementById("preview");
var fields = div.getElementsByTagName("input");
var len = fields.length;
var num = len -1;
var Current = new Array();
var MaxValue=len;
var NumUnique=len ;
var Count=0;
var Current = new Array(NumUnique);
GetUnique();
alert("The unique numbers are: " + Current[0] + ", " + Current[1] + ", and " + Current[2])
function GetUnique()
{
for (i=0;Count<NumUnique;Count++)
{
Found=false
var rndValue = get_random()
var j=0
for (j=0;j<Current.length;j++)
{
if (Current[j] == rndValue)
{
Found=true
break
}
}
if (Found)
{
Count--
} else {
Current[Count]=rndValue
}
}
}
function get_random()
{
var ranNum= Math.round(Math.random()*MaxValue);
return ranNum;
}
// End -->
</script>
calling it here....this may be problem but not sure how to resolve it
<input name="Randomise" value="Randomise question order" onclick="GetUnique(this)" type="submit" title="Submit" />