user1086348
user1086348

Reputation: 81

can't get javascript function to execute

I'm a beginner with Javascript and can't get the code below to work. When I click the button, nothing happens. Could someone point out what I did wrong? Thanks!

<html>
<head>
<title>Sarah's Puppy Game</title>
</head>
<body>
    <div id="input">
        <input id="puppyNumber" size=30>
        <button onClick="doLoop()"> Get your puppies </button>
    </div>
    <script type="text/html">
        function doLoop() {
        var number = document.getElementById('puppyNumber').value;
            var puppy = [];
            while (var i = 0; i < parseInt(number); i++) {
                puppy = puppy.push('puppy<br>');
            }
            alert(puppy);


        }
    </script>
</body>
</html>

Upvotes: 2

Views: 128

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270757

Three problems I see.

  1. First, use text/javascript for the <script type='text/javascript'>

  2. Second, change while to for in your loop. A while loop is for testing against a condition, but you have setup a counter.

  3. Thrid, don't assign puppy with the push() method. .push() acts directly on the array.

Here's the corrected version in action.

<!-- type="text/javascript" not "text/html" -->
<script type="text/javascript">
    function doLoop() {
    var number = document.getElementById('puppyNumber').value;
        var puppy = [];

        // This is a for loop, rather than a while loop
        // Also for good measure, use the second param to parseInt() for a
        // decimal radix to avoid getting binary or octal numbers accidentally.
        for (var i = 0; i < parseInt(number, 10); i++) {
            // Don't assign the result back to puppy
            puppy.push('puppy<br>');
        }
        alert(puppy);


    }
</script>

Upvotes: 5

Jon Newmuis
Jon Newmuis

Reputation: 26530

Instead of...

puppy = puppy.push('puppy<br>');

...just say...

puppy.push('puppy<br>');

push returns the element that was pushed, not the array to which it was pushed.

Your code will cause the variable puppy to be set to the string "puppy<br>". Then you'll try to do "puppy<br>".push("puppy<br>"), which is obviously invalid.

Upvotes: 1

Related Questions