gpt4 book ai didi

javascript - 如何将表格内的表单转换为JSON

转载 作者:行者123 更新时间:2023-12-01 02:39:02 25 4
gpt4 key购买 nike

我正在尝试将表单数据转换为 json我有一个 html 表如下。在表单提交上我想要做的是将其转换为 json

<form class="sales-order-form">
<table class="table">
<tbody>
<tr>
<th>Item Name</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Free Quantity</th>
<th>Sub Total</th>
</tr>
<tr>
<td><select class="form-control" name="itemName" style="width: 250px;">
<option></option>
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</select></td>
<td><input class="form-control" name="unitPrice" type="text" readonly="readonly" value="50">
</td>
</tr>
<tr>
<td><select class="form-control" name="itemName" style="width: 250px;">
<option></option>
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</select></td>
<td><input class="form-control" name="unitPrice" type="text" readonly="readonly" value="50">
</td>
</tr>
</tbody>
</table>
</form>

在表单提交时,如何将此表单转换为以下 json?

[
{
"itemName": "item1",
"unitPrice": "49"
},
{
"itemName": "item2",
"unitPrice": "56"
}
]

如何做到这一点?

我尝试遵循

function getFormData($salesOrderForm){
var unindexed_array = $salesOrderForm.serializeArray();
var indexed_array = {};

$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});

return indexed_array;
}

但是它只返回一个json

{
"itemName": "item1",
"unitPrice": "50"
}

最佳答案

您可以使用 document.getElementsByName("unitPrice") 获取元素详细信息和document.getElementsByName("itemName")

试试这个:

  function getFormData() {
let res = [];
let x = document.getElementsByName("unitPrice");
let y = document.getElementsByName("itemName");

for (let i = 0; i < x.length; i++) {
let obj = {
"itemName": x[i].value,
"unitPrice": y[i].value
}
res.push(obj);
}
console.log(res);
}
  <form class="sales-order-form">
<table class="table">
<tbody>
<tr>
<th>Item Name</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Free Quantity</th>
<th>Sub Total</th>
</tr>
<tr>
<td><select class="form-control" name="itemName" style="width: 250px;">
<option></option>
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</select></td>
<td><input class="form-control" name="unitPrice" type="text" readonly="readonly" value="50">
</td>
</tr>
<tr>
<td><select class="form-control" name="itemName" style="width: 250px;">
<option></option>
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</select></td>
<td><input class="form-control" name="unitPrice" type="text" readonly="readonly" value="50">
</td>
</tr>
</tbody>
</table>
</form>
<button onclick="getFormData()">getFormData</button>

关于javascript - 如何将表格内的表单转换为JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59279410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com