英文:
Submit modal form and get fields as JSON
问题
我有一个简单的模态框(div),用于在HTML中提交表单。
<div class="modal-body">
<form id="myform">
<div class="form-group">
<label for="username">Username</label>
<input type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" placeholder="Password" class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-sm btn-outline-secondary" onclick="addToFirebase()">Save changes</button>
</div>
当我尝试以JSON格式获取表单字段数据时,我得到了空数组[]。我需要将所有字段值以JSON格式获取。
function addToFirebase(){
alert('Adding to firebase');
var formData = JSON.stringify($("#myform").serializeArray());
console.log(formData);
}
英文:
i have simple modal div to submit form in html
<div class="modal-body">
<form id="myform">
<div class="form-group">
<label for="username">Username</label>
<input type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" placeholder="Password" class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-sm btn-outline-secondary" onclick="addToFirebase()">Save changes</button>
</div>
when i am trying to get the fields data in form of json i am getting blank array [] . I need to get all field values as json .
function addToFirebase(){
alert('Adding to firebase');
var formData = JSON.stringify($("#myform").serializeArray());
console.log(formData);
}
答案1
得分: 0
表单元素缺少 name
属性。例如:
<input name="username" type="text" placeholder="用户名" class="form-control">
在序列化表单时,name
用作键/值对中的键。没有 name
,就没有可分配值的键。
此外... 为了正确关联 <label>
元素,表单输入还需要一个与 for
属性匹配的 id
:
<input name="username" id="username" type="text" placeholder="用户名" class="form-control">
英文:
The form elements are missing name
attributes. For example:
<input name="username" type="text" placeholder="Username" class="form-control">
The name
is used as the key in key/value pairs when serializing a form. Without one, there's no key to which the value can be assigned.
As an aside... For the <label>
elements to be properly associated, the form inputs also need an id
to match the for
attributes:
<input name="username" id="username" type="text" placeholder="Username" class="form-control">
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论