I have run into an issue where an input field within a form I’m using should only be shown under certain conditions. I chose to display it with jQuery’s dialog() method. However, after the dialog() method is called, any subsequent calls to jQuery’s serialize() method will leave out that input field from the generated string. I suspect that this is somehow due to dialog() removing the element from the form or something along those lines, but I can’t seem to find a fix.
Here is the HTML and JS to reproduce the issue:
HTML:
<form id="form">
<div id="dialog" style="display: none;">
<input type="text" name="foo" value="bar" />
</div>
<!-- Other form inputs here -->
</form>
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);
}
}
});
Edit:
There are several other inputs within the form that should not be shown on the dialog, so putting the form tags within the dialog div is not an option for me.
@NicolaPeluchetti offered one possible solution, but I found this one to be less of a hassle:
In the
dialog()call options, I added the following:Basically, it sticks
#dialogback into#formwhen the dialog is closed. This won’t help if you need the input to be part of the form while the dialog is open, but in my case, I only needed it to be available after the dialog was closed.