Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Fall 2019

## Add Another

Example: add_another.html | Add Another in JSFiddle

JavaScript:

- select the "div" we want to duplicate
- clone the "div" to create a new one
- change the id (to maintain uniqueness) of the new div
- insert the new div into the document

    $(document).ready(function() {
        var numberofphones = 1;
        $('#addphone').click(function() {
          numberofphones++;
          newid = 'phone' + numberofphones;
          var phonediv = $('#phone1');
          var newphonediv = phonediv.clone();
          newphonediv.attr('id',newid);
          newphonediv.insertBefore('#addphone');
      });
     });

Markup:

    <form action="http://cscie12.dce.harvard.edu/echo" method="get">
      <fieldset>
        <legend>Contact Information</legend>
        <div>Name:
          <input type="text" name="name"/></div>
        <div id="phone1">Phone:
          <input type="text" name="phone"/> </div>
          <input type="button" id="addphone" value="Add another phone"/>
      </fieldset>
      <div><input type="submit"/></div>
    </form>

Copyright © David Heitmeyer