I'm very new at all of this and I need to create a JavaScript for loop that prints out the numbers 1 to 10 when a button is clicked and -1 to -10 when another button is clicked as the attached screenshot shows.
I've done this but I'm very stuck.
<!DOCTYPE html>
<html>
<body>
<h1>For loop statement exercise</h1>
<p>Press PLUS to display 1 to 10:
<button onclick="plus()">PLUS</button>
<p>Press MINUS to display -1 to -10:
<button onclick="myFunction()">MINUS</button>
<p id="i"></p>
<script>
for (i = 1; i <= 10; i )
{
document.write("i" < br > );
}
</script>
</body>
</html>
CodePudding user response:
Try this
<!DOCTYPE html>
<html>
<body>
<h1>For loop statement exercise</h1>
<p>
Press PLUS to display 1 to 10: <button onclick="plus()">PLUS</button>
</p>
<p>
Press MINUS to display -1 to -10:
<button onclick="minus()">MINUS</button>
</p>
<p id="i"></p>
<script>
function minus() {
for (i = -1; i >= -10; i--) {
document.getElementById("i").innerHTML =
document.getElementById("i").innerHTML `${i} <br>`;
}
}
function plus() {
for (i = 1; i <= 10; i ) {
document.getElementById("i").innerHTML =
document.getElementById("i").innerHTML `${i} <br>`;
}
}
</script>
</body>
</html>
CodePudding user response:
I don't know if you want it to add a number every time you click or add them all in just one click, but I did this:
<!DOCTYPE html>
<html>
<body>
<h1>For loop statement exercise</h1>
<p>Press PLUS to display 1 to 10:</p>
<button onclick="plus()">PLUS</button>
<p id=" "></p>
<p>Press MINUS to display -1 to -10:</p>
<button onclick="minus()">MINUS</button>
<p id="-"></p>
<script>
function plus() {
for(let i = 1; i <= 10; i ) {
document.getElementById(" ").innerHTML = i " ";
}
}
function minus() {
for(let i = -1; i >= -10; i--) {
document.getElementById("-").innerHTML = i " ";
}
}
</script>
</body>
</html>