[英]jQuery get closest form on button click
i want to make an ajax request when i press on the form button i need to get the form itself my code is我想在按下表单按钮时发出ajax请求我需要获取表单本身我的代码是
$(document).ready(function() {
$(document).on('click', '.finalEdit', function (e) {
e.preventDefault();
var form = $(this).closest('form');
$.ajax({
data: form.serialize(),
url: form.attr('action'),
type: "POST",
dataType: "html",
success: function (result) {
// feel free to execute any code
// in the success callback
$('#divToRefresh').html(result);
},
error: function (result) {
alert("Failed");
}
})
return false;
});
$(this).closest('form') gets another form in the page i don't know why $(this).closest('form') 在页面中获取另一个表单我不知道为什么
this is the form i am looking for这是我要找的表格
<tr hidden="hidden">
@using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { @class = "Edit-form" }))
{
@Html.ValidationSummary(true)
<td>
@Html.HiddenFor(model => model.supplier.SupplierID, new { @Value = item.SupplierID })
</td>
<td>
@Html.TextBoxFor(model => model.supplier.SupplierName, new { @Value = item.SupplierName })
</td>
<td>
<input type="submit" value="Edit" class="finalEdit"/>
</td>
}
</tr>
If the .finalEdit
button is within the form tags, you can use this.form
to get the form that the element belongs to.如果
.finalEdit
按钮在表单标签内,您可以使用this.form
获取元素所属的表单。 You can then wrap it in $()
to get a jQuery object of the form element: var form = $(this.form);
然后,您可以将其包装在
$()
中以获取表单元素的 jQuery 对象: var form = $(this.form);
. .
If it's not finding the form, make sure that the tags are properly nested and closed.如果未找到表单,请确保标签已正确嵌套和闭合。 Also make sure that the input does not have a
form
attribute .还要确保输入没有
form
属性。
the $(this).closest('form')
wasn't getting another form. $(this).closest('form')
没有得到另一种形式。 it didn't get any form actually.它实际上没有得到任何形式。
i don't know why .closest('form')
didn't work in that scenario我不知道为什么
.closest('form')
在那种情况下不起作用
anyways this line of code worked for me无论如何,这行代码对我有用
var form = $(this).parent().parent().children(":first");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.