I am loading a from dynamically onto the page, I then setup the event to capture and handle the form submit.
But for whatever reason the form, still does the usual post and goes to the page instead of the ajax post.
I'm pretty sure its all correct but can't figure out why?
I load the form dynamically like this:
$('body').on('click', 'a[data-toggle="modal"]', function (e) {
var action = $(this).attr('href');
$.ajax({
url: action,
type: "GET",
success: function (response) {
$('<div class="modal fade"></div>').html(response).modal();
hookupFormSubmit();
}
});
e.preventDefault();
});
hookupFormSubmit looks like this:
var hookupFormSubmit = function () {
$('.modal-dialog').on('submit', 'form', function (event) {
event.preventDefault();
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(data, status) {
$form.closest('.modal').modal('hide');
}
});
});
};
And my form itself:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
@Html.EditorForModel()
<p>
<input type="submit" value="Send Message!" />
</p>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>