我有一个可以通过两个按钮提交的表单。我想要一个按钮来简单地保存表单的内容,另一个按钮来保存内容然后清除它。我正在使用ajax提交表单。我目前有两个名称相同的按钮,每个按钮都包含不同的值。这是我的html按钮,
//Saves the form
<button type="submit" name="action" value="save_form"
class="btn btn-success">Save</button>
//Saves the form and clears it
<button type="submit" name="action" value="new_form"
class="btn btn-warning">New Form</button>
我使用ajax提交表单,这是我用来获取提交表单的操作按钮值的代码,
'action' : $('button[name=action]').val()
整个过程有效,但问题是当我使用new_form
按钮提交表单时,上面的jQuery代码仍然将提交按钮的值设置为save_card
而不是new card
我已经切换了按钮在表单上的显示顺序,上面的jQuery代码获取了首先出现的名为action
的按钮的值。
为什么这样做?如何检测提交表单的按钮?
通过Ajax提交表单的jQuery
$(document).on('submit', '#edit_form', function(event) {
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
// get the form data
var formData = {
'did' : $('input[name=did]').val(),
'front' : $('textarea[name=front]').val(),
'back' : $('textarea[name=back]').val(),
'cid' : $('input[name=cid]').val(),
'action' : $('button[name=action]').val()
};
// process the form
$.ajax({
type : 'POST',
url : '../API/api.php',
data : formData,
success: function(data) {
//do something
}
});
});
答案 0 :(得分:2)
如果您在按钮的点击事件中调用'action' : $('button[name=action]').val()
,请使用
'action' : $(this).val().
$(this)
将引用被点击的元素。并且$('button[name=action]')
将返回具有name = action的所有按钮,并且您有两个名为action的按钮,因此返回的是首次遇到的任何按钮。
<强>更新强>
尝试以下内容:
$('button[name=action]').click(function(event) {
// stop the form from submitting the normal way and refreshing the page
// get the form data
var formData = {
'did' : $('input[name=did]').val(),
'front' : $('textarea[name=front]').val(),
'back' : $('textarea[name=back]').val(),
'cid' : $('input[name=cid]').val(),
'action' : $(this).val()
};
// process the form
$.ajax({
type : 'POST',
url : '../API/api.php',
data : formData,
success: function(data) {
//do something
}
});
});