简体   繁体   中英

Javascript: Creating Multiple Li Items with Button Onclick Function

I am trying to create an application to display a certain number of list items based on the number input (ie 3 = 3 list items). So far I have only been able to create a function that displays one list item with the onClick function. No matter what code I use, I cannot find a way to create multiple list items from one button click. Here is my current code, HTML:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
   <section>
       <header>Week 5 Assignment</header>
       <section>
           <label>Name: <input type="text" id="nameInput" value="Enter a Name"></label>
       </section>
    <section>
        <label>Num of Times: <input type="number" id="numInput" value="Enter Number"></label>
        <section>
           <ol id="nameOutput"></ol>
           <hr>
          <button onclick="displayName();">Display Name!</button> 
          <button>Reset</button> 
       </section>
    </section>
   </section>

    <script src="script.js"></script>
</body>
</html>

And my JS:

    var name = document.getElementById("nameInput").value;
    console.log(name);

    var num = document.getElementById("numInput").value;

    var list = document.getElementById("nameOutput");

    var item = document.createElement("li");

    item.innerText = name;
    list.append(item);
}

Javascript For loop should work for what you are trying to achieve

 <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <section> <header>Week 5 Assignment</header> <section> <label>Name: <input type="text" id="nameInput" value="Enter a Name"></label> </section> <section> <label>Num of Times: <input type="number" id="numInput" value="Enter Number"></label> <section> <ol id="nameOutput"></ol> <hr> <button onclick="displayName();">Display Name!</button> <button>Reset</button> </section> </section> </section> <script src="script.js"></script> </body> </html> <script> function displayName() { var name = document.getElementById("nameInput").value; var num = document.getElementById("numInput").value; var item = document.createElement("li"); item.innerText = name; document.getElementById("nameOutput").innerHTML = ''; for (i = 0; i < num; i++) { document.getElementById("nameOutput").innerHTML += '<li>'+name+'</li>'; } } </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM