Creating an arbitrary number of child fields with jQuery
<p>I'm trying to create a form that contains contacts. There can be an arbitrary number of contacts and each contact can have an arbitrary number of emails and phone numbers. I'm using jQuery to create additional fields and everything's working fine until you add a new contact and try to add arbitrary child fields to it. I can't figure out how to add them to the form so they're associated with the contact block that called the function.</p>

<p>Here's the basic HTML I'm trying to use, simplified to show the issue.</p>

<pre><code>&lt;div class="contactinfo"&gt;
    Contact: &lt;input name="contactname" type="text" /&gt;&lt;br /&gt;
    &lt;div class="contactemail"&gt;
        Email: &lt;input name="contactemail" type="text" /&gt;&lt;br /&gt;
    &lt;/div&gt;
    &lt;a href="javascript:addEmail()"&gt;Add Email&lt;/a&gt;&lt;br /&gt;
&lt;/div&gt;
&lt;a href="javascript:addContact()"&gt;Add Contact&lt;/a&gt;&lt;br /&gt;
</code></pre>

<p>And here's the jQuery:</p>

<pre><code>function addEmail() {
    var newemail = '&lt;div class="contactemail"&gt;' +
        'Email: &lt;input name="contactemail" type="text" /&gt;&lt;br /&gt;' +
        '&lt;/div&gt;';
    $('.contactemail:last').append(newemail);
}

function addContact() {
    var newcontact = '&lt;div class="contactinfo"&gt;' +
      'Contact: &lt;input name="contactname" type="text" /&gt;&lt;br /&gt;' +
      '&lt;div class="contactemail"&gt;' +
      'Email: &lt;input name="contactemail" type="text" /&gt;&lt;br /&gt;' +
      '&lt;/div&gt;' +
      '&lt;a href="javascript:addEmail()"&gt;Add Email&lt;/a&gt;&lt;br /&gt;' +
      '&lt;/div&gt;';
    $('.contactinfo:last').append(newcontact);      
}
</code></pre>

<p>(I know that <code>:last</code> isn't the correct selector.)</p>

<p>Is there a way I can know which contact block called the function and where to append the new HTML? Is this the wrong approach altogether? I'd appreciate any input I could get. Thank you very much.</p>
