Reputation: 81
I'm trying to create a function that first selects a random number, and then print every number starting at 1 through the random number, on the page.
Basically, it should look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 twenty five 26 27 28 29 30 31 32 33 34 35
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 seventy five 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
124 one hundred and twenty five
Here's the function that I have so far. Currently, it's simply alerting a bunch of random numbers. How do I get it so that it doesn't alert the numbers, but writes them on the page itself? Any help would be greatly appreciated.
<script>
function randomNumber() {
var num = Math.floor(Math.random() * 200);
var english = {
25 : "twenty five",
75 : "seventy five",
125 : "one hundred and twenty five"
}
for (var i = 0; i < 200; i++) {
var num = Math.floor(Math.random() * 200);
alert(num);
}
}
document.getElementById('yourElement').onclick = randomNumber();
</script>
Upvotes: 0
Views: 95
Reputation: 2488
You have set the event listener in a wrong way.
document.getElementById('yourElement').onclick = randomNumber();
When you use "onclick = randomNumber()" you are not setting the function randomNumber to onclick. Because you wrote "()" after the function, you are actually calling the function and the thing that is set to onclick is actually the return value of randomNumber, which is in your case "undefined".
This piece of code should do what you want.
<script type="text/javascript">
window.onload = function() {
var english = {
25 : 'twenty five'
// and so on
}
function randomNumber() {
var r = Math.round( Math.random() * 200 )
return english[r] || r;
}
function writeRandomNumber() {
this.innerHTML += randomNumber();
}
document.getElementById('yourElement').onclick = writeRandomNumber;
}
</script>
Upvotes: 1
Reputation: 31141
Use innerText, innerHTML, or textContent to set the text of an element:
document.getElementById("myElement").innerText += num;
Upvotes: 0