Friday, September 25, 2009

How to copy a field value from a jQuery UI Dialog into a form

If you have a form on your page, and would like to display a jQuery dialog which prompts for some extra data to add to the form before you submit it, here's how you can do it:

<SCRIPT language=JavaScript>
function copyValueAndSubmit() {
$('#popupDiv').dialog("destroy").appendTo("#myForm");
$("#myForm").submit();
}

$(function() {$('#popupDiv').dialog({autoOpen: false});});
</SCRIPT>

<form id="myForm" name="myForm">
<input id="field1"/>
<input id="field2"/>
<button type="button" onclick="$('#popupDiv').dialog('open');">Save</button>
</form>

<div style="visibility:hidden;">
<div id="popupDiv">
<input id="field3"/>
<button type="button" onclick="copyValueAndSubmit();">Submit</button>
</div>
</div>



Basically, the
.dialog("destroy").appendTo("#myForm")
call allows you to grab whatever was in the popup dialog and append it to the form on your page before it gets submitted.

0 comments: