Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

creating and appending variables inside a for loop

I’m trying to dynamically make an unordered list using javascript, where I just have to list the number of items that I want and it will display it in the list.

example input prompt "how many list items would you like?" if we input 2 and enter
it should return

  <ul>
    
    <li>hi</li>
    <li>hi</li>
    
    </ul>

I’ve simplified the HTML and javascript but i tried wrap the append and create variables in a for loop and nothing happened.
heres the code html :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    const numberofitemsel = document.getElementById('num-of-navitems');
        const numberofitems = parseInt(numberofitemsel.value);
    
        const body = document.body;
    
    
        const savebtn = document.getElementById('save');
       savebtn.addEventListener('click',()=>{
        let ul =document.createElement("ul");
    // append to body 
    
    
    
       body.append(ul);
       // create list items 
       
       for(var i=0;i<=numberofitems;i++){
        let li=document.createElement("li");
        li.innerText="hi";
 
 
 
 
 
    // append to ul
    ul.appendChild(li);
   }
});
   

 <main>
      <h4>how many list items do you want?</h4>
      <input type="number" id="num-of-navitems">
      <button type="button" id="save">save</button>
    </main>

so the output I want is the if I input 3 into my input box I want three list items:

<ul>

<li>hi</li>
<li>hi</li>
<li>hi</li>

</ul>

>Solution :

You should use for loop in the savebtn.eventListener:

for(let i=0;i<Math.floor(Number(numberofitemsel.value));i++) {
 let li = document.createElement("li");
 li.innerText = "hi";
 // append to ul
 ul.appendChild(li);
  }

The other parts of your code are OK.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading