我有类似的表格:
<form class="submission-form" method="POST" action="/post/create/">
<input type="text" name="title">
<textarea name="post_content"></textarea>
<select name="visibility" class="form-control">
<option value="1">Public</option>
<option value="2">Private</option>
</select>
<input class="submit-button" type="button" value="Publish">
</form>
表格中的各个字段事先是未知的,可以改变;众所周知,每个需要处理的表单都有一个submission-form
类,它包含一个类submit-button
的按钮。
我试图在input.submit-button
上添加一个事件监听器,它将遍历其包含的表单,查找所有字段,并从中创建一个对象。例如,在上面的例子中,创建的对象可能如下所示:
{
title: "My first post",
post_content: "Hello there!",
visibility: 1
}
我该怎么做呢?
答案 0 :(得分:2)
迭代输入,textarea和select元素,并使用元素名称和值的属性创建一个对象:
$('.submit-button').on('click', function() {
var o = {};
$(this).closest('form')
.find('input, textarea, select')
.not(':button')
.each(function() {
o[$(this).attr('name')] = $(this).val()
});
console.log(o);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="submission-form" method="POST" action="/post/create/">
<input type="text" name="title" />
<textarea name="post_content"></textarea>
<select name="visibility" class="form-control">
<option value="1">Public</option>
<option value="2">Private</option>
</select>
<input class="submit-button" type="button" value="Publish" />
</form>
&#13;
<强>参考强>
答案 1 :(得分:1)
您可以使用serializeArray()
然后在该数组上使用reduce()
来返回所需的对象。
$("form").submit(function(event) {
var data = $(this).serializeArray().reduce(function(r, e) {
r[e.name] = e.value;
return r;
}, {})
console.log(data)
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="submission-form">
<input type="text" name="title">
<textarea name="post_content"></textarea>
<select name="visibility" class="form-control">
<option value="1">Public</option>
<option value="2">Private</option>
</select>
<input class="submit-button" type="submit" value="Publish">
</form>
答案 2 :(得分:1)
使用serializeArray()
为名称值对创建对象数组并循环遍历它们以创建单个对象。
$('form').submit(function(e){
e.preventDefault();
var obj = $(this).serializeArray()
var final= {};
$.each(obj, function(index,object){
final[object.name] = object.value;
});
console.log(final);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="submission-form" method="POST" action="/post/create/">
<input type="text" name="title">
<textarea name="post_content"></textarea>
<select name="visibility" class="form-control">
<option value="1">Public</option>
<option value="2">Private</option>
</select>
<input class="submit-button" type="submit" value="Publish">
</form>
&#13;