SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Oct 2011
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Jquery clone method

    Hi all,
    I want to display a text field with a plus sign next to it. The user can then click the plus sign which duplicates the text field on a new line with another plus sign. The user can then continue doing this.

    Ive had an initial stab at the code, and it clones the first text field fine, but when you click on the second plus sign, it creates 2 more text fields, and then clicking on one of the new plus signs creates 4 new text fields, the next one creates 8 new text fields etc...!

    How can I have this so only one text field is created each time the plus sign is clicked.

    My code is:

    js:
    Code:
    $(document).ready(function() { 
             $(".add-but").click(function () {
                $('.single-code').first().clone(true).attr('class','single-code').insertAfter(".single-code").last();      
            });
          });

    html:
    Code HTML4Strict:
    <div class="single-code">
    <div class="controls">
    <input type="text"><a href="#" class="add-but"><img src="img/add.png" width="16" height="16"></a>
    </div>
    </div>
    Last edited by spikeZ; Oct 8, 2012 at 05:54.

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,347
    Mentioned
    179 Post(s)
    Tagged
    9 Thread(s)
    You could create a container div for all of the clones and just keep appending new elements to this.

    HTML Code:
    <!DOCTYPE html>
      <html>
        <head>
        <title>Title</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
      </head>
      
      <body>
        <div id="master">
          <div><input type="text"><a href="#" class="add-but"><img src="img/add.png" width="16" height="16"></a></div>
        </div>
        <div class="clones"></div>
        
        <script>
          $(document).ready(function() { 
            $(".add-but").live('click', function () {
              $(".clones").append($("#master").html());
            });
          });
        </script>
      </body>
    </html>

  3. #3
    SitePoint Member
    Join Date
    Oct 2011
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thats great Pullo - thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •