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>
2 Answers 2
Three problems I see.
First, use
text/javascriptfor the<script type='text/javascript'>Second, change
whiletoforin your loop. Awhileloop is for testing against a condition, but you have setup a counter.Thrid, don't assign
puppywith thepush()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>
Comments
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.
3 Comments
while(i < number) { puppy.push(str); i++ }
alertstatements to get a glimpse of what's happening.