PDA

View Full Version : Random Text w/ Button


mrkwlkn
02-04-2003, 02:11 PM
I would like the number to be random every time the button is pressed. What is wrong with the following code?

=======================================

<SCRIPT>
var item=new Array(
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9");

function randselect() {
do { i=Math.floor(Math.random()*item.length); }
while(typeof(item[i])=="undefined"); return item[i];
}
</SCRIPT>

<BODY>
<INPUT TYPE="button" value="Select New Random Number" ONCLICK="document.value=randselect();">
<P>
<SCRIPT>document.write(randselect());</SCRIPT>

=======================================

Thanks in advance.

Jon Hanlon
02-04-2003, 05:20 PM
You can't just do a 'document.write()' and change page content. The easist way is to put the result in a text area.
Later browsers have a getElementById() method and you can use the .innerHTML property. And then there's NN4 layers...




<script language="Javascript">
function randomRange(inMin,inMax) {
var min = 0, max = 0;
if (inMin) min = inMin;
if (inMax) max = inMax;
if (min > max) {
var swop = min
min = max
max = swop
}
return min + Math.floor(Math.random() * (max - min + 1))
}

function genRandom(formObj) {
var rnd = randomRange(1,9)
formObj.resultText.value = rnd;
if (document.getElementById)
document.getElementById("resultDiv").innerHTML = rnd;
}
</script>

<form>
<INPUT TYPE="button" value="Select New Random Number" ONCLICK="genRandom(this.form)">
<input type="text" name="resultText">
</form>

<div id="resultDiv"></div>

mrkwlkn
02-05-2003, 01:21 AM
Cool, thanks it works fine now.