【问题标题】:Using user input for javascript function (for loop)Using user input for javascript function (for loop)
【发布时间】:2022-12-01 14:23:46
【问题描述】:

I have a basic js function that connects to my html file. I want the user to input a number and then the function will count up to that number. As it counts it will display a circle with each number. So, input 3 and you'll see three circles counting 1, 2, 3 horizontally on the page.

When I call the function and hard code an input like:

display(9)

it works fine. I console log my user input, I console log as I loop through and it's counting just fine, but for some reason,

const button = document.getElementById("button");
const main = document.querySelector("main");


let number = "";

function display(num) {
  for (let i = 1; i <= num; i++) {
    console.log("in the loop " + i);
    number += `<div>${i}</div>`;
  }
}

button.addEventListener('click', () => {
  let input = parseInt(document.getElementById("input").value);
  console.log(input);
  display(input);
});

document.getElementById("display").innerHTML = number;
<h1 class="h1">Test Form</h1>

<input class="input" id="input" type="text" />
<input type="button" id="button" value="Enter" />

<p class="display" id="display"></p>

it won't display anything using user input.

My code is below. Thoughts? And thank you for the help!

【问题讨论】:

  • document.getElementById("display").innerHTML = number; this line of code needs to be after for loop.

标签: javascript html for-loop input user-input


【解决方案1】:

You just add the following statements to the end of display function to make it work.

  let displayDiv=document.getElementByI("display");
  displayDiv.innerHTML=number;     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2016-09-28
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多