...

View Full Version : what am I missing?



gencoglu
06-18-2007, 12:29 PM
I tested the following script but it did not work :confused:
Could you please fix the problem ? so I can learn more about firstchild and node...
Thanks





<html>

<head>
<script>
window.onload = function()
{
sortN();
}

function sortN() {
for(var m = 1; m <= 6; m++) {
arr[m] = Math.floor(Math.random() * 49) + 1;
}
arr.sort();
var sorted;
for(var m = 1; m <= 6; m++) {
sorted += arr[m] + "\n";
}
var kut = document.getElementById('kut');
if (kut) kut.firstChild.nodeValue += sorted;

}


</script>
</head>
<body>
<pre id="kut">&nbsp;</pre>
</body>
</html>

Philip M
06-18-2007, 01:09 PM
<html>

<head>
<script type = "text/JavaScript">
function sortN() {
var arr = new Array();
for (var m = 1; m <= 6; m++) { // array values index 1-6
var x = Math.floor(Math.random() * 49) + 1;
if (x<10) {x = "0" + x} // add leading zero to single digits for sort
arr[m] = x;
}

arr.sort(); // sort() is performed as ASCII not numeric
var sorted = ""; // initialise value

for (var m = 0; m <= 5; m++) { // sorted array index 0 -5
var y = arr[m].toString(); // must be a string now
var z = y.substr(0,1); // identify first character
if (z == "0") {y = y.substr(1,1)} // delete leading zeroes again
sorted += y + "\n";
}

var kut = document.getElementById('kut');
if (kut) kut.firstChild.nodeValue += sorted;
}
</script>
</head>
<body onload="sortN()" >
<pre id="kut">&nbsp;</pre>
</body>
</html>

P.S. kut is a naughty word in Dutch!

1212jtraceur
06-18-2007, 02:58 PM
To clarify Philip's code (if you didn't see it, gencoglu), you didn't declare arr before assigning properties to it.

gencoglu
06-19-2007, 01:00 PM
Thanks for your reply..Now what we get is only one single line of six numbers..
I will add a "setInterval ()" function to write one line at a time..and I need line under line...
I tried "<br>" but it did not work..Can we use "<div>" instead of "<pre>" ?
whats more..sometime there are dublicated numbers..so we need to avoid them..
thanks

Philip M
06-19-2007, 01:50 PM
Here's the modification to eliminate duplicate numbers:-

function sortN() {
var arr = new Array();
for (var m = 1; m <= 6; m++) { // array values index 1-6
var x = Math.floor(Math.random() * 49) + 1;
arr[m] = x;
if (m > 0) {
for (var j=0; j<arr.length-1; j++) {
if (x == arr[j]) {m = m-1; break} //check for repeated elements and get another number if duplicated
}
}
if (x < 10) {x = "0" + x} // add leading zero to single digits for sort
arr[m] = x;
}

sorted is a single variable containing six concatenated numbers so you cannot write it out line by line.

You need:-

for (j=0; j<=5; j++) { // 6 data values
document.write (arr[j] + "<br>");
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum