如何使用javascript将复选框添加到列表中

问题描述 投票:0回答:1

我在生成时将复选框添加到列表中时遇到问题。我希望能够检查或取消选中使用addToList函数添加的项目。

我试过玩html,并在javascript中创建一个函数,但仍然没有成功。

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);
};


function addToPantry () {
  for (i = 0; i<foodlist.length; i++){
    let name = foodlist[0];
    pantry.push(`${name}: [${amount}, [${unit}]]`)
  }


````
HTML
````

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

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

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

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

<ul id="foodlist"></ul>
javascript list checkbox append
1个回答
1
投票

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

  let input = document.createElement('input');
  input.type = "checkbox";
  input.addEventListener('change', deleteTodo);

  let li = document.createElement("li");
  li.textContent = food + ' ' + amount + ' ' + unit + '.';
  li.appendChild(input);
  document.getElementById("foodlist").appendChild(li);
};


function addToPantry() {
  for (i = 0; i < foodlist.length; i++) {
    let name = foodlist[0];
    pantry.push(`${name}: [${amount}, [${unit}]]`)
  }
}

function deleteTodo(e) {
  e.currentTarget.parentNode.remove(e);
}
<input type="text" name="" value="food" id="food">
<input type="text" name="" value="amount" id="amount">


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

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

<ul id="foodlist"></ul>
© www.soinside.com 2019 - 2024. All rights reserved.