Monday, March 21, 2011

JQuery Dialog Remove Form Elements

I have used JQuery UI Dialog box as a container to hold some of my form elements, and show it after a button click. Somehow, all these elements that covered under the Jquery Dialog DIV failed to POST back to the server.
JQuery Dialog seems removed the form element out from the original dom structure, thus causing the problem. The solution will be
1) Add an additional DIV or SPAN  before your closing FORM tag(give it an ID), 
2) Before the form submit, append the Dialog DIV back to the above created DIV or SPAN

Here's the sample code:

<!DOCTYPE html>
<html lang="en">
<?php
if($_POST['username']) echo "<br/> Username is " . $_POST['username'];
if($_POST['outerfield']) echo "<br/> Username is " . $_POST['outerfield'];
?>
<head>
<meta charset="utf-8">
<title>jQuery demo</title>
</head>
<body>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/jquery-ui.css" type="text/css" media="screen">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<script>
//google.load("jquery", "1.5.1");
//google.load("jqueryui", "1.8.11");
</script>
<form id="form1" method='post'>
<input type="button" class="button" value="go dialog" onclick="GoDialog()" />
<input type='button' class='button' value='Check Value1' onclick='checkvalue("outerfield");'>
<input type='button' class='button' value='Check Value2' onclick='checkvalue("username");'>
<input type='button' class='button' value='Put It Back' onclick='putitback("username");'>
<br/> OuterField <input type='text' name='outerfield' size='20'>
<div class="dlg" id="msgDlg" style='display:none;'>
<br/>Name: <input type="text" name='username' />
<br/><input type="button" class="button" value="OK" onclick="$('#msgDlg').dialog('close');" />
</div>
<div id="beforesubmit" style="display:none"></div>

<script>
$(function () {
$('#msgDlg').dialog({
autoOpen: false,
modal: false,
width: 450,
height: 300,
draggable: true,
resizable: true
});

});

$("#form1").submit(function() {
$("#msgDlg").prependTo("#beforesubmit");

});

function GoDialog() {
var msgDlg = $('#msgDlg').dialog('open');
}
</script>
<br/><input type='submit' value='Submit'>
</form>
</body>
</html>
<script>
function checkvalue(fieldname){
if(document.forms[0][fieldname]==undefined){
alert(fieldname+' Undefined detected');
}else{
alert(fieldname+' - Okay');
}
}
</script><