Note that there are some explanatory texts on larger screens.

plurals
  1. POCopying from form to form in jQuery
    text
    copied!<p>I had a requirement to copy all fields from one form to another similar form. So instead of copying field by field I wrote a routine, form2form, using jQuery.</p> <pre><code>function form2form(aF1, aF2) { var selection = "#" + aF1 + " .copy"; $(selection).each(function() { document.forms[aF2].elements[$(this).attr('name')].value = $(this).val(); }); } </code></pre> <p>the routine works. The routine requires that in input form field have a class of copy otherwise I don't know how to get all fields in the form. ("#form :input") skips the radio button and select fields.</p> <p>So my questions are.</p> <p>Is there a built in function so I didn't need this? Is there a better way to write the selection? How do I modify the routine not to need the class. Can I pass form objects rather then the form name as a text? Is there a better way in general?</p> <p>this is a full page that works:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;test form2form in jQuery&lt;/title&gt; &lt;script type="text/javascript" src="../scripts/jquery.js"&gt;&lt;/script&gt;&lt;/head&gt; &lt;script type="text/javascript"&gt; function form2form(aF1, aF2) { var selection = "#" + aF1 + " .copy"; $(selection).each(function() { document.forms[aF2].elements[$(this).attr('name')].value = $(this).val(); }); } function testform2form () { form2form ('form1', 'form2' ); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;Copy form to form&lt;/h3&gt; &lt;form id="form1" name="form1"&gt; form1: f1 &lt;input type="text" name="f1" id="f1" class="copy" value="from A"/&gt; f2 &lt;input type="text" name="f2" id="f2" class="copy" value="from B" /&gt; &lt;select name="fruit" id="fruit" class="copy" &gt; &lt;option value="valApple" selected="selected"&gt;Apple&lt;/option&gt; &lt;option value="valOrange"&gt;Orange&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;form id="form2" name="form2"&gt; form1: f1 &lt;input type="text" name="f1" id="f1" class="copy" value="target A" /&gt; f2 &lt;input type="text" name="f2" id="f2" class="copy" value="target B" /&gt; &lt;select name="fruit" id="fruit" class="copy" &gt; &lt;option value="valApple"&gt;Apple&lt;/option&gt; &lt;option value="valOrange" selected="selected"&gt;Orange&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;p&gt;&lt;a href="#" onclick="testform2form()"&gt;Copy Form to Form (form2form)&lt;/a&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload