-2

I am making a javascript code that has a button and when I click on it, it displays one of 5 symbols but when I click the button, it shows the random symbol but the button disapears. I'm new to javascript so can I please get some help?

<script>

function slots()
{
    var slot1 = Math.floor(Math.random()*5);
    if (slot1 == 0) {
        document.write("\u2663");
    }
    if (slot1 == 1) {
        document.write("\u2665");
    }
    if (slot1 == 2) {
        document.write("\u2666");
    }
    if (slot1 == 3) {
        document.write("\u2660");
    }
    if (slot1 == 4) {
        document.write("7");
    }
}

</script>
<button type="button" value="Spin" name="SPIN"onClick="slots(); return false;"></button>
shellco
  • 536
  • 1
  • 6
  • 25
Tuckertcs
  • 29
  • 5
  • 1
    Take a look at [this question](http://stackoverflow.com/questions/13741584/what-does-document-write-do). – chazsolo Apr 01 '15 at 00:45

2 Answers2

2

When you write document.write() the screen refreshes, so I guess you could do something like this:

<script>

function slots()
{
    var slot1 = Math.floor(Math.random()*5);
    if (slot1 == 0) {
        document.getElementById('value').innerHTML = "\u2663";
    }
    if (slot1 == 1) {
        document.getElementById('value').innerHTML = "\u2665";
    }
    if (slot1 == 2) {
        document.getElementById('value').innerHTML = "\u2666";
    }
    if (slot1 == 3) {
        document.getElementById('value').innerHTML = "\u2660";
    }
    if (slot1 == 4) {
        document.getElementById('value').innerHTML = "7";
    }

}
</script>

<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
cdonts
  • 9,304
  • 4
  • 46
  • 72
Don Beto
  • 132
  • 4
  • 12
  • Not at all, go on. I just added what was needed. – Don Beto Apr 01 '15 at 02:58
  • That's alright, I actually wrote it in a separate answer - in your case I'd switch `if`s to `else if`s for a tiny performance gain (more because it's a good practice to show to beginners). – Shomz Apr 01 '15 at 03:07
  • @Tuckertcs Glad to help, could you mark my question as the answer? ;) – Don Beto Apr 01 '15 at 20:54
0

Slightly optimized version of otrebla's code, see it in action:

function slots() {
  var slot1 = Math.floor(Math.random() * 5);
  var value = document.getElementById('value');
  switch (slot1) {
    case 0:
      value.innerHTML = "\u2663";
      break;
    case 1:
      value.innerHTML = "\u2665";
      break;
    case 2:
      value.innerHTML = "\u2666";
      break;
    case 3:
      value.innerHTML = "\u2660";
      break;
    case 4:
      value.innerHTML = "7";
      break;
  }
}
<button type="button" value="Spin" name="SPIN" onClick="slots();">Click</button>
<span id="value"></span>
Shomz
  • 37,421
  • 4
  • 57
  • 85