最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create and fill list item with a button? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to create a list of items to be displayed, using data entered into a text field. My trouble is that when I want to add a second list item, the first one just updates. I've tried a few different things and I'm stuck.

function addToList() {
  let food = document.getElementById("food").value;
  let amount = document.getElementById("amount").value;
  let unit = document.getElementById("unit").value;

  document.getElementById("foodlist").innerHTML =
    (food + ' ' + amount + ' ' + unit + '.')

};
<input type="text" name="" value="food" id="food"><br>
<input type="text" name="" value="amount" id="amount"><br>

<select id="unit">
  <option value="oz">ounces</option>
  <option value="lb">pounds</option>
  <option value="servings">servings</option>
</select><br>

<button onclick="addToList()" type="button" name="button" id="addButton">add</button><br>

<li id="foodlist"></li>

I'm trying to create a list of items to be displayed, using data entered into a text field. My trouble is that when I want to add a second list item, the first one just updates. I've tried a few different things and I'm stuck.

function addToList() {
  let food = document.getElementById("food").value;
  let amount = document.getElementById("amount").value;
  let unit = document.getElementById("unit").value;

  document.getElementById("foodlist").innerHTML =
    (food + ' ' + amount + ' ' + unit + '.')

};
<input type="text" name="" value="food" id="food"><br>
<input type="text" name="" value="amount" id="amount"><br>

<select id="unit">
  <option value="oz">ounces</option>
  <option value="lb">pounds</option>
  <option value="servings">servings</option>
</select><br>

<button onclick="addToList()" type="button" name="button" id="addButton">add</button><br>

<li id="foodlist"></li>

I want the data from the text fields to create a new list item and add the data to an object every time the button is pressed. all I have gotten so far is the list item just keeps updating.

Share Improve this question edited Mar 26, 2019 at 10:26 Masoud Keshavarz 2,2449 gold badges40 silver badges49 bronze badges asked Mar 26, 2019 at 7:46 zrwhite151zrwhite151 791 gold badge2 silver badges8 bronze badges 1
  • Possible duplicate of how to add new <li> to <ul> onclick with javascript – Arkellys Commented Mar 26, 2019 at 7:53
Add a ment  | 

5 Answers 5

Reset to default 2

You would need to create a ul element and dynamically create li elements, then append them as children of this ul. See code below:

function addToList() {
  let food = document.getElementById("food").value;
  let amount = document.getElementById("amount").value;
  let unit = document.getElementById("unit").value;

  let li = document.createElement("li");
  li.textContent = food + ' ' + amount + ' ' + unit + '.';
  document.getElementById("foodlist").appendChild(li);
}
<input type="text" name="" value="food" id="food">
<br>
<input type="text" name="" value="amount" id="amount">
<br>

<select id="unit">
  <option value="oz">ounces</option>
  <option value="lb">pounds</option>
  <option value="servings">servings</option>
</select>

<br>
<button onclick="addToList()" type="button" name="button" id="addButton">add</button>
<br>
<ul id="foodlist"></ul>

The reason is because you did not create a new list element when you want to append a new item, which is why it keeps replacing the initial value and updating the initial element.

Just need to append new list node to the DOM with the following code when you add a new item and you are all set.

function addToList() {
  let food = document.getElementById("food").value;
  let amount = document.getElementById("amount").value;
  let unit = document.getElementById("unit").value;
  
  var node = document.createElement("LI");                 
  var textnode = document.createTextNode(food + ' ' + amount + ' ' + unit + '.');       
  node.appendChild(textnode); 
  document.getElementById("foodlist").appendChild(node)
    

};
<input type="text" name="" value="food" id="food">
<br>
<input type="text" name="" value="amount" id="amount">
<br>

<select id="unit">
  <option value="oz">ounces</option>
  <option value="lb">pounds</option>
  <option value="servings">servings</option>
</select>

<br>
<button onclick="addToList()" type="button" name="button" id="addButton">add</button>
<br>
<ul id="foodlist"></ul>

Try to append the content.

please change this line document.getElementById("foodlist").innerHTML = to document.getElementById("foodlist").innerHTML +=

and change <li id="foodlist"></li> to <ul id="foodlist"></ul>

and (food + ' ' + amount + ' ' + unit + '.') to ('<li>'+food + ' ' + amount + ' ' + unit + '.</li>')

function addToList() {
  let food = document.getElementById("food").value;
  let amount = document.getElementById("amount").value;
  let unit = document.getElementById("unit").value;

  document.getElementById("foodlist").innerHTML +=
    ('<li>'+food + ' ' + amount + ' ' + unit + '.</li>')

};
<input type="text" name="" value="food" id="food">
<br>
<input type="text" name="" value="amount" id="amount">
<br>

<select id="unit">
  <option value="oz">ounces</option>
  <option value="lb">pounds</option>
  <option value="servings">servings</option>
</select>

<br>
<button onclick="addToList()" type="button" name="button" id="addButton">add</button>
<br>
<ul id="foodlist"></ul>

That's because you replace everything using innerHTML. You could just re-use the existing HTML like this (using += instead of +):

function addToList() {
  let food = document.getElementById("food").value;
  let amount = document.getElementById("amount").value;
  let unit = document.getElementById("unit").value;

  document.getElementById("foodlist").innerHTML +=
    ('<li>' + food + ' ' + amount + ' ' + unit + '.' + '</li>')

};
<input type="text" name="" value="food" id="food">
<br>
<input type="text" name="" value="amount" id="amount">
<br>

<select id="unit">
  <option value="oz">ounces</option>
  <option value="lb">pounds</option>
  <option value="servings">servings</option>
</select>

<br>
<button onclick="addToList()" type="button" name="button" id="addButton">add</button>
<br>
<ul id="foodlist"></ul>

You cannot add li elements to a li element - the parent element must be one of eith UL or OL

Each click of the button should call a function to add a new DOM element to the parent node - in this case it will add a new li element as required with the content from the other form elements

<!DOCTYPE html>
<html>
    <head>
        <style>
            form{width:60%;font-family:calibri,verdana,arial}
            label{display:block;width:90%;clear:both;float:none;margin:1rem auto;padding:1rem 0 }
            label > input, label > select{float:right;width:80%;padding:1rem;margin:-1rem;}
            label:before{content:attr(for);text-transform:capitalize}
            button{padding:1rem;width:100%;}
        </style>
        <script>
            document.addEventListener('DOMContentLoaded',e=>{
                let form=document.querySelector('form');
                let food=document.querySelector('input[type="text"][name="food"]');
                let amount=document.querySelector('input[type="text"][name="amount"]');
                let list=document.querySelector('ul[id="foodlist"]');
                let bttn=document.querySelector('button[name="button"]');
                let unit=document.querySelector('select[name="unit"]');




                bttn.addEventListener('click', e=>{
                    let li=document.createElement('li');
                        li.innerText = [
                            food.value,
                            amount.value,
                            unit.value
                        ].join(' ');
                    list.appendChild( li );
                    form.reset();
                })
            });
        </script>
    </head>
    <body>
        <form method='post'>
            <label for='food'><input type='text' name='food' placeholder='Food - eg: Venison' /></label>
            <label for='amount'><input type='text' name='amount' placeholder='Amount - eg: 45' /></label>
            <label for='unit'>
                <select name='unit'>
                    <option selected hidden disabled>Please select
                    <optgroup label='Weight'>
                        <option value='oz'>Ounces
                        <option value='lb'>Pounds
                        <option value='gr'>Grams
                    </optgroup>
                    <optgroup label='Volume'>
                        <option value='ml'>Millilitre
                        <option value='l'>Litres
                        <option value='gall'>Gallons
                    </optgroup>
                    <optgroup label='Misc'>
                        <option value='servings'>Servings
                        <option value='items'>Items
                    </optgroup>
                </select>
            </label>
            <button type='button' name='button'>Add</button>
        </form>

        <!-- LI elements are added to a UL, OL or DL -->
        <ul id='foodlist'></ul>
    </body>
</html>
发布评论

评论列表(0)

  1. 暂无评论