jQuery对话框/序列化冲突?

FtD*_*Xw6 3 forms jquery serialization dialog

我遇到了一个问题,我正在使用的表单中的输入字段只能在某些条件下显示.我选择用jQuery的dialog()方法显示它.但是,在dialog()调用该方法之后,对jQuery serialize()方法的任何后续调用都将从生成的字符串中省略该输入字段.我怀疑这是由于dialog()从表单中删除元素或沿着这些行的东西,但我似乎无法找到修复.

以下是重现问题的HTML和JS:

HTML:

<form id="form">
    <div id="dialog" style="display: none;">
        <input type="text" name="foo" value="bar" />
    </div>
    <!-- Other form inputs here -->
</form>
Run Code Online (Sandbox Code Playgroud)

JS:

alert($('#form').serialize()); // "foo=bar"
$('#dialog').dialog({
    buttons: {
        OK: function() {
            alert($('#form').serialize()); // Should be "foo=bar", but is "" instead?
            $(this).dialog('close');
            alert($('#form').serialize()); // Still "".
            setTimeout(function() {
                alert($('#form').serialize()); // Still "".
            }, 0);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑:

表单中还有其他几个输入不应显示在对话框中,因此将form标记放在对话框div中对我来说不是一个选项.

Nic*_*tti 6

是的,这是因为对话框改变了标记,因为它可以在对话框中包含表单标记

<div id="dialog" style="display: none;">
    <form id="form">
        <input type="text" name="foo" value="bar" />
    </form>
</div>
Run Code Online (Sandbox Code Playgroud)

编辑 - 如果你不能把表格标签你必须使用隐藏字段并保持与jquery同步,我害怕

<form id="form">
    <div id="dialog" style="display: none;">
        <input type="text" name="foo_dialog" class='dialog' value="bar" />
    </div>
    <input type="hidden" name="foo" value="" />
    <!-- Other form inputs here -->
</form>
Run Code Online (Sandbox Code Playgroud)

JS

$('input.dialog').keyup(function(){
    var name = this.name.replace('_dialog', '');
    $('input:hidden[name='+name+']').val(this.value);
});
Run Code Online (Sandbox Code Playgroud)