jquery post form from dialog
i have a js function which gets html to create new employee from controller, inserts it inside a form tag (for later .serialize()), and then inserts this html to createDialog div and shows this div as dialog.
<div id="createDialog" style="display:none;">
</div>
$.get('/Employee/Create',
function (html) {
html = "<form id='createEmp'>" + html;
html = html + "</form>";
$("#createDialog").html(html);
$("#createDialog").dialog({
modal: true,
width: 500,
buttons: { "Save": function () { postEmployee(); } },
close: function (ev, ui) { $(this).dialog('destroy'); }
});
});
fun开发者_如何学编程ction postEmployee() {
$.post('/Employee/Create',
$("#createEmp").serialize(),
function (html) {
$('#reply').html(html);
});
}
this works, but only once. with every next post all form fields from previous posts are also added to current post. can this be fixed ?
Tahnk You !
You also need to remove the <form>
element you created, like this:
close: function (ev, ui) { $(this).dialog('destroy').empty(); }
You can also make the whole function a bit cleaner with .wrapInner()
like this:
$.get('/Employee/Create', function (html) {
$("#createDialog").html(html).wrapInner("<form id='createEmp'> />");
$("#createDialog").dialog({
modal: true,
width: 500,
buttons: { "Save": postEmployee },
close: function (ev, ui) { $(this).dialog('destroy').empty(); }
});
});
It is better to not create and destroy but to create and then open and close.
html
<div id="createDialog" style="display:none;">
</div>
js
var $dialog = $("#createDialog").dialog({
modal: true,
autoOpen: false,
width: 500,
buttons: { "Save": function () { postEmployee(); } },
close: function (ev, ui) { $(this).dialog('close'); }
});
$.get('/Employee/Create', function (html) {
html = "<form id='createEmp'>" + html;
html = html + "</form>";
$("#createDialog").html(html);
$dialog.dialog("open");
});
function postEmployee() {
$.post('/Employee/Create',
$("#createEmp").serialize(),
function (html) {
$('#reply').html(html);
});
}
$.get('/Employee/Create',
function (html) {
var nodeContent= "<form id='createEmp'>" + html + "</form>";
$("#createDialog").empty();
$("#createDialog").html(nodeContent);
$("#createDialog").dialog({
modal: true,
width: 500,
buttons: { "Save": function () { postEmployee(); } },
close: function (ev, ui) { $(this).dialog('destroy'); }
});
});
Use the excellent jquery form plugin from malsup: http://malsup.com/jquery/form/
Call clearForm() on success:
function postEmployee()
$('#createEmp').ajaxSubmit({
url: '/Employee/Create'
, success: function(html){
$('#reply').html(html);
$('#createEmp').clearForm();
}
});
}
Call resetForm() after creating the form to prevent the browser from restoring cached values.
$('#createEmp').resetForm();
精彩评论