Harvard Extension School, Fall 2018
CSCI E-12 Fundamentals of Web Site Development

## Chaining jQuery

- calculate the new "id" string
- select the phone div to be duplicated
- duplicate (clone) the phone div
- change the id of the new phone div
- insert the new phone div into the document

jQuery methods return nodes, so we can easily chain these steps together.

Stepwise:

    $(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');
      });
     });

Chained:

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

Copyright © David Heitmeyer