开发者

jQuery Dialog posting of form fields

I'm trying to do some data entry via a jQuery modal Dialog. I was hoping to use something like the following to gather up my da开发者_StackOverflowta for posting.

data = $('#myDialog').serialize();

However this results in nothing. If I reference just the containing form instead myDialog then I get all the fields on the page except those within my dialog.

What's the best way to gather up form fields within a dialog for an AJAX submission?


The reason this is happening is that dialog is actually removing your elements and adding them at root level in the document body. This is done so that the dialog script can be confident in its positioning (to be sure that the data being dialog'd isn't contained, say, in a relatively positioned element). This means that your fields are in fact no longer contained in your form.

You can still get their values through accessing the individual fields by id (or anything like it), but if you want to use a handy serialize function, you're going to need to have a form within the dialog.


I've just run into exactly the same problem and since I had too many fields in my dialog to reference them individually, what I did was wrap the dialog into a temporary form, serialize it and append the result to my original form's serialized data before doing the ajax call:

function getDialogData(dialogId) {
    var tempForm = document.createElement("form");
    tempForm.id = "tempForm";
    tempForm.innerHTML = $(dialogId).html();
    document.appendChild(tempForm);
    var dialogData = $("#tempForm").serialize();
    document.removeChild(tempForm);
    return dialogData;
}

function submitForm() {
    var data = $("#MyForm").serialize();
    var dialogData = getDialogData("#MyDialog");
    data += "&" + dialogData;
    $.ajax({
        url: "MyPage.aspx",
        type: "POST",
        data: data,
        dataType: "html",
        success: function(html) {
            MyCallback(html);
        }
    });
}


Form element inside dialog is removed from form and moved to the end of the body. You need something like this.

 $("#dialog_id").dialog().parent().appendTo($("#form_id"));


jQuery("#test").dialog({
           autoResize:true,
           width:500,
           height:600,
           modal: true,
           bgiframe: true,
           }).parent().appendTo("form");

This works like charm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜