0

I want to generate 15 random numbers in the range 1-18 and assign them values. Here is my code. The problem is, when I press the button, the text displayed by Javascript, is 15 random items from the list I gave, which is exactly what I want, however, these items replace the 'Scramble' button. I want the button to stay so that I can generate another random list without reloading the page.

<!DOCTYPE html>
<html>
<head>
<title>text/javascript</title>
<script language="javascript"> 
function myFunction() {
document.getElementById('Scramble');
for (var i = 0; i < 15; i++) {
var x = Math.floor((Math.random()*18)+1)
if (x === 1) {
    document.write("R ")
};
if (x === 2) {
    document.write("R' ")
};
if (x === 3) {
    document.write("R2 ")
};
if (x === 4) {
    document.write("L ")
};
if (x === 5) {
    document.write("L' ")
};
if (x === 6) {
    document.write("L2 ")
};
if (x === 7) {
    document.write("F ")
};
if (x === 8) {
    document.write("F' ")
};
if (x === 9) {
    document.write("F2 ")
};
if (x === 10) {
    document.write("B ")
};
if (x === 11) {
    document.write("B' ")
};
if (x === 12) {
    document.write("B2 ")
};
if (x === 13) {
    document.write("U ")
};
if (x === 14) {
    document.write("U' ")
};
if (x === 15) {
    document.write("U2 ")
};
if (x === 16) {
    document.write("D ")
};
if (x === 17) {
    document.write("D' ")
};
if (x === 18) {
    document.write("D2 ")
};
};
};
</script>
</head>
<body>
<button onclick="myFunction()">Scramble</button>
<p id="Scramble"></p>
</body>
</html>
  • 1
    The root of the problem is the fact you'e using [`document.write`](http://stackoverflow.com/a/802943/791010). – James Thorpe Oct 15 '15 at 11:37
  • 1
    Would be much more logical to have an array of strings `var arr = ["R", "R'", "R2", ...]` then directly call `document.write(arr[x])`. Note that with this you'd need to remove that `+1` from your `x` variable assignment. – James Donnelly Oct 15 '15 at 11:41

2 Answers2

0

If you use document.write, you'll write directly in the document so you'll erase the previous data.

If you want to write in the #Scramble element, you use innerHtml :

var Scramble = document.getElementById('Scramble');
Scramble.innerHtml = 'new content';
Magus
  • 13,609
  • 2
  • 31
  • 47
0

replace all the document.write(); with document.getElementById('Scramble').innerHTML= "string you want to display";

as you can see here

Dario Rusignuolo
  • 1,822
  • 5
  • 33
  • 61
  • w3school is not considered as a trusted source. So Please don't provide links to w3schools. http://meta.stackoverflow.com/questions/280478/why-not-w3schools-com – niyasc Oct 15 '15 at 12:45
  • Instead you may use this link, https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML – niyasc Oct 15 '15 at 12:46