如何将用户输入功能与HTML中的表格链接?

时间:2018-10-05 08:17:49

标签: javascript html css visual-studio

我在浏览器中创建了一个包含两个部分(“杂货名称”和“价格”)的“购物清单”表,并且有一个供用户输入杂货名称的字段。我希望每次用户在字段中输入一个项目并按下“ ADD”按钮或输入时,都可以将该项目放入表格部分。

var groceries = []
document.querySelector('#addGroceryForm').addEventListener('submit', addGrocery)


function addGrocery(event) {
  event.preventDefault() //stop the form submission(re-loading the page)
  var groceryInput = document.querySelector('#groceryInput')
  groceries.push(groceryInput.value)
  //Add the new column to the table;
  groceryInput.value = ''

  updateGroceries()
}

function updateGroceries() {
  var groceriesElement = document.querySelector('#groceries')
  groceriesElement.innerHTML = ''

  for (var currentIndex = 0; currentIndex < groceries.length; currentIndex++) {
    var grocery = groceries[currentIndex]
    groceriesElement.innerHTML += '<li>' + grocery + '</li>'
  }
}
<form id="addGroceryForm" method='post'>
  <input id='groceryInput' type='text' placeholder="Enter Food">
  <button type='submit'>ADD</button>
</form>

<table class="table-fill">
  <thead>
    <tr>
      <th class="text-left">Item</th>
      <th class="text-left">Price</th>
    </tr>
  </thead>
  <tbody class=groceries>
    <tr>
      <td></td>
      <td class="groceryInput"></td>
    </tr>
    <tr>
      <td class="text-left" id='leftOne'> </td>
      <td class="text-left">£</td>
    </tr>
    <tr>
      <td class="text-left"> </td>
      <td class="text-left">£</td>
    </tr>
    <tr>
      <td class="text-left"> </td>
      <td class="text-left">£</td>
    </tr>
    <tr>
      <td class="text-left"> </td>
      <td class="text-left">£</td>
    </tr>
  </tbody>
</table>

0 个答案:

没有答案