我如何从汇总的表单中获取所有数据并将其添加到新列表中

2022-06-06 00:00:00 key-value forms javascript form-data

我想把提交的所有数据做成一个列表(-Item:bannana-itemNum:#3330...)

<form id="form" action="">
  <h3>Item:</h3>
  <input name="item" type="text">
  <h3>Item numbers:</h3>
  <input name="itemNum" type="number">
  <h3>Quantity:</h3>
  <input name="quantity" type="number">
  <h3> Price:</h3>
  <input name="price" type="number">
  <h3>Discount:</h3>
  <input name="discount" type="number">
  <br>
  <button id="but">Submit</button>
</form>

解决方案

只有一行:

let formInputs = Object.fromEntries( new FormData(myForm).entries() ) 

参见FormData

在上下文中:

数据-lang="js"数据-隐藏="真"数据-控制台="真"数据-巴贝尔="假">
myForm = document.querySelector('#myForm')

myForm.onsubmit = evt =>
  {
  evt.preventDefault() // disable submit   page reload
  console.clear()
 
  let formInputs = Object.fromEntries( new FormData(myForm).entries() ) 

  console.log( formInputs )
}
body, textarea, input {
  font-family : Helvetica, Arial sans-serif;
  font-size   : 12px;
  }
label {
  font-size   : 1.2em;
  display     : block;
  float       : left;
  clear       : both;
  width       : 10em;
  white-space : nowrap;
  overflow    : hidden;
  font-weight : bold;
  padding-top : .7em;
  line-height: 1.4em;
  }
label:after {
  content     : '....................................'; 
  font-weight : normal;
  color       : lightslategray;
  }
input {
  display     : block;
  float       : left;
  width       : 5em;
  margin      : .3em;
  }
button {
  display     : block;
  float       : left;
  clear       : both;
  margin-top  : .6em;
  }
.as-console-wrapper { max-height:100% !important; top:0; left:50% !important; width:50%; }
.as-console-row         { background-color: yellow; }
.as-console-row::after  { display:none !important; }
<form id="myForm" action="">
  <label> Item:</label>         <input name="item"     type="text"   >
  <label> Item numbers:</label> <input name="itemNum"  type="number" >
  <label> Quantity:</label>     <input name="quantity" type="number" >
  <label> Price:</label>        <input name="price"    type="number" >
  <label> Discount:</label>     <input name="discount" type="number" >
 
  <button type="submit">Submit</button>
</form>

相关文章