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 :
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>
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.
You need to evaluate numberofitemsel.value
after the user clicks the button, not before.
const numberOfItemsEl = document.getElementById('num-of-navitems');
const body = document.body;
const savebtn = document.getElementById('save');
savebtn.addEventListener('click', () => {
const numberOfItems = parseInt(numberOfItemsEl.value);
const ul = document.createElement("ul");
body.append(ul);
for (let i = 0; i < numberOfItems; i++) {
const li = document.createElement("li");
li.innerText = "hi";
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>
const main = document.querySelector("#main");
const mainUl = document.querySelector("#mainUl");
const inputText = document.querySelector("#textInput");
const taskBtn = document.querySelector("#addTask");
function addTask(times) {
for (var i = 0; i < times; i++) {
const li = document.createElement("li");
li.innerHTML = "hi";
mainUl.appendChild(li);
}
}
taskBtn.addEventListener("click", () => {
if (inputText.value == "") {
alert("please enter number!!");
} else {
addTask(inputText.value);
inputText.value = "";
}
});
<div id="main">
<input type="text" id="textInput" placeholder="Enter Number" />
<button id="addTask">Add List</button><br />
<ul id="mainUl"></ul>
</div>