gpt4 book ai didi

javascript - 序列化表单并更改输入名称(删除输入名称的数组部分)

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

我想序列化我的html表单并通过ajax将其提交到我的服务器,但在提交表单之前,我想重命名变量名称并删除首字母部分,即:BranchViewModels[0]. 例如,我想更改:

更改:BranchViewModels[0].BranchName 为:BranchName

更改:BranchViewModels[1].AddressViewModel.AddressId 为:AddressViewModel.AddressId

基本上,当我生成表单时,所有输入名称都会呈现为数组,但在提交表单之前,我想删除输入名称的数组部分(本例中为 BranchViewModels[0].)。

我已经解释了为什么我要这样做here

我还创建了一个jsfiddle对于以下示例。

function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serialize();
alert('I want to change the input names in this serialized form: \n\n' + serializedform );

// 1. iterated through serialized form
//
// remove BranchViewModels[i]. from the name, e.g.
// replace: BranchViewModels[0].BranchName
// with: BranchName


// 2. Submit the form
/* $.ajax({
url: "/my-server",
data: {branchViewModel: <-- serialized model},
dataType: 'json',
type: "POST"}); */
});
}

jQuery(document).ready(function($) {
updateBranch();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form onsubmit="return false;" novalidate="novalidate">
<div class="form">

<div class="form-group">
<label>Branch name</label>
<input class="form-control" data-val="true" id="BranchViewModels_0__BranchName" name="BranchViewModels[0].BranchName" type="text" value="branch 1">
</div>

<hr />

<div class="form-group">
<label>Branch location</label>
<div>
<input data-val="true" id="BranchViewModels_0__AddressViewModel_AddressId" name="BranchViewModels[0].AddressViewModel.AddressId" value="1956">
</div>

<div>
<input class="address-street-address" data-val="true" id="BranchViewModels_0__AddressViewModel_StreetAddress" name="BranchViewModels[0].AddressViewModel.StreetAddress" value="Wellington 6011, New Zealand">
</div>
</div>

<input type="button" class="btn btn-primary-action save-branch-button" value="Save">

</div>
</form>

最佳答案

function updateBranch() {
$('.save-branch-button').click(function() {
var branchForm = $(this).closest('form');
var serializedform = branchForm.find('.form :input').serializeArray();
console.log(serializedform);
const obj = {};
for(let d of serializedform){
obj[d.name.split('.').pop()] = d.value
}
console.log(obj);
}

关于javascript - 序列化表单并更改输入名称(删除输入名称的数组部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60332474/

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