When I write in something in the prompt I get underfined. When I write something in the prompt I want that to add in the list like a new list-element. For example if I write "Food" in the prompt I want it to say "Food" on the second line. Now it adds a new list-element but it's empty. Here is my code:
var items = document.querySelector('items');
function addItemToList() {
var newItem = prompt("Add item to list");
if (newItem != null) {
var ul = document.querySelector('ul');
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML = li.value;
}
}
<ul id="items">
<li>Drinks</li>
</ul>
<input class="buttom-add" type="button" id="btnAdd" value="Add Item" onclick="addItemToList()">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You are setting the newly appended li
's innerHTML
to its value
property (which is 0) instead of the value returned by prompt
.
Instead, assign newItem
to the li
's innerHTML
property:
var items = document.querySelector('items');
function addItemToList() {
var newItem = prompt("Add item to list");
if (newItem != null) {
var ul = document.querySelector('ul');
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML = newItem;
}
}
<ul id="items">
<li>Drinks</li>
</ul>
<input class="buttom-add" type="button" id="btnAdd" value="Add Item" onclick="addItemToList()">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You just need to change the last line with li.innerHTML = newItem;
so that you assign the item read from the prompt.
var items = document.querySelector('items');
function addItemToList() {
var newItem = prompt("Add item to list");
if (newItem != null) {
var ul = document.querySelector('ul');
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML = newItem;
}
}
<ul id="items">
<li>Drinks</li>
</ul>
<input class="buttom-add" type="button" id="btnAdd" value="Add Item" onclick="addItemToList()">
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>