0

Im learning Javascript, completely new to it. I am trying to write some code that will deal random cards from the array with each click of the button. It doesn't have to remove the cards just deal random ones. I was able to get the button to deal the first card, but the button disappears in place of the card name and im not able to deal any further. My question is how can keep the button there and have it dealing cards with each click. This is my code:

<div>
<button type="button" onclick="document.write(randomcard())"> Deal Card </button>
</div>
<script>



var cardsInDeck = new Array();


cardsInDeck[0] = "Ace of spades";
cardsInDeck[1] = "ace of clubs";
cardsInDeck[2] = "ace of diamonds";
cardsInDeck[3] = "ace of hearts"
cardsInDeck[4] = "King of diamonds"

function randomcard(){ return cardsInDeck[Math.floor(Math.random()*cardsInDeck.length)]
}


</script>

any help is greatly appreciated.

user3355961
  • 635
  • 2
  • 15
  • 32

1 Answers1

0

Following code works for me

HTML part

<button type="button" onclick="randomcard()"> Deal Card </button>
<br><h7 id="result"></h7>

JavaScript part

var cardsInDeck = new Array();
cardsInDeck[0] = "Ace of spades";
cardsInDeck[1] = "ace of clubs";
cardsInDeck[2] = "ace of diamonds";
cardsInDeck[3] = "ace of hearts"
cardsInDeck[4] = "King of diamonds"

function randomcard(){
var res = document.getElementById("result");
res.innerHTML=cardsInDeck[Math.floor(Math.random()*cardsInDeck.length)];

See it working http://jsfiddle.net/fNPvf/5066/

What you were missing was a place/label to view your output, I just added that and it works perfectly now. Hope it helped.

Rijul Gupta
  • 915
  • 10
  • 18