JQuery dialog / serialize conflict?
I am facing an issue where the input field inside the form I am using should only be displayed under certain conditions. I decided to display it using jQuery method dialog()
. However, once the method is called, dialog()
any subsequent calls to the jQuery method serialize()
will exclude that input field from the generated string. I suspect it has something to do with dialog()
removing the item from the form or something near these lines, but I can't seem to find a fix.
Here's the HTML and JS to reproduce the problem:
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 in the form that shouldn't appear in the dialog, so placing tags form
in the dialog div
is not an option for me.
source to share
@NicolaPeluchetti suggested one possible solution, but I found it not that hard:
In the call parameters, dialog()
I added the following:
close: function() {
$(this).appendTo('#form');
}
Basically, it closes #dialog
back in #form
when the dialog is closed. It won't help if you need the input to be part of the form while the dialog is open, but in my case I needed it to be available after the dialog was closed.
source to share
Yes, this is because the dialog is changing the markup as it should work with the form tag in the dialog
<div id="dialog" style="display: none;">
<form id="form">
<input type="text" name="foo" value="bar" />
</form>
</div>
EDIT - if you can't put the form tag, you will have to use hidden fields and sync with jquery, I'm afraid
<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>
Js
$('input.dialog').keyup(function(){
var name = this.name.replace('_dialog', '');
$('input:hidden[name='+name+']').val(this.value);
});
source to share
I had a similar problem where I was filling out a dialog with form
Ajax loaded content and serializing it.
form
was serialized like this:
var form = $('#encuesta').serialize();
function genera() {
$.ajax({
type: "POST",
url: "genera_encuesta.php",
data: form,
success: function(datos) {
$('#res1').html(datos);
}
});
}
I solved it by doing:
function genera() {
var form = $('#encuesta').serialize();
$.ajax({
type: "POST",
url: "genera_encuesta.php",
data: form,
success: function(datos) {
$('#res1').html(datos);
}
});
}
....
Hope this helps someone a ton not to waste a lot of time.
source to share