Reputation: 147
i want to make an ajax request when i press on the form button i need to get the form itself my code is
$(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 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>
Upvotes: 1
Views: 4635
Reputation: 81
If the .finalEdit
button is within the form tags, you can use this.form
to get the form that the element belongs to. You can then wrap it in $()
to get a jQuery object of the form element: 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.
Upvotes: 2
Reputation: 147
the $(this).closest('form')
wasn't getting another form. it didn't get any form actually.
i don't know why .closest('form')
didn't work in that scenario
anyways this line of code worked for me
var form = $(this).parent().parent().children(":first");
Upvotes: 0