-4

I am having trouble displaying images using a while loop using a function showCards(7) to output the HTML to display the images. I believe my problem lies somewhere within the JS function but I can't seem to be able to figure it out.

This assignment is to create a black jack game although this first part should only display 7 cards.

Below is the HTML and JS:

<table border=0 style='margin:auto'>
    <tr>
        <td>
            <form>
                <input type="BUTTON" onClick="Javascript:alert('Dummy Link')" value="Deal > > >">
            </form>
        </td>

        <script type="text/javascript">showCards(7)</script>

        <td>
            <form>
                <input type="BUTTON" onClick="Javascript:alert('Dummy Link')" value="< < < Hit Me">
            </form>
        </td>
    </tr>
</table>

function showCards(7) {
    while (true) {
        document.writeln("< IMG src='http://www.college1.com/images/cards/gbCard52.gif' width=30 height=30 >")
        count = count + 1
    }
}
sjrd
  • 21,805
  • 2
  • 61
  • 91
  • Note: Using `document.writeln()` and similar after the initial load of the `document` has completed, including once the user can `click` on an element, will open a new `document`, clearing all of the previously existing content. If that's not the intention, see "[What are alternatives to document.write?](http://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write)" – Jonathan Lonowski Oct 18 '14 at 22:25

2 Answers2

1

The problem is with your truthy in the while() loop. You should modify it to use a for() loop as follows:

function showCards( arg ) 
{
    for(var i = 0; i < arg; i++)
    {
         document.writeln("< IMG src='http://www.college1.com/images/cards/gbCard52.gif' width=30 height=30 >"); 
    }
}

Notice that the showCards() function now accepts an argument, which should be the number of cards to be added.

BenM
  • 52,573
  • 26
  • 113
  • 168
1

You have made an infinite loop, so the code will just keep writing out image tags until the browser stops the script for taking too long to run.

Lets start with the function declaration. You have used the number 7 where you would use a parameter name:

function showCards(cardCount) {

You use a counter inside the loop, which is good, but you should initialise the counter before the loop:

var count = 0;

You should make the loop run as long as there are more images to write out:

while (count < cardCount) {

So:

function showCards(cardCount) {
  var count = 0;
  while (count < cardCount) {
    document.writeln("< IMG src='http://www.college1.com/images/cards/gbCard52.gif' width=30 height=30 >");
    count = count + 1;
  }
}

You can also use a for loop to do the same thing:

function showCards(cardCount) {
  for (var count = 0; count < cardCount; count++) {
    document.writeln("< IMG src='http://www.college1.com/images/cards/gbCard52.gif' width=30 height=30 >");
  }
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005