HPWD
HPWD

Reputation: 2240

jquery clone not showing up where I expected

I have a form with input fields and the client can click a button located at the bottom of the field, "Add a System". This function will clone a div with an id="template". so far so good.

Existing Form
Existing Form
Existing Form
Cloned 3
Cloned 2
Cloned 1
Add a System Button

but what I need it to do is move the cloned template as teh very last item just above the Add a system button:

Existing Form
Existing Form
Existing Form
Cloned 1
Cloned 2
Cloned 3
Add a System Button

where Cloned 3 is the where the template will appear the 3rd time the button is clicked. If the user adds 20 systems, the button and the field aren't even on teh screen at the same time. I looked for an insertBefore but apparently that doesn't exists in JavaScript.

JS Code:

function AddNewSystem(){    
    alert('Adding new system');
    var CurrentLi = $('.template');
    CurrentLi.clone().insertAfter( $('#cloned') );
}

Here is a jsfiddle to see what I'm talking about. Click the "Add a System" button at and where the word template appears, change it to a 1 (or 2 or 3, etc) and repeat this at least 3 times. By this point you should see how the template is inserting.

Is there a better way to clone than what I'm doing?

Upvotes: 2

Views: 691

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206199

you can append them directly to #cloned

function Repeat()
  {
    var CurrentLi = $('.template').eq(0);
    CurrentLi.clone().appendTo('#cloned');
  }

fiddle demo*

p.s. i changed #template to class. It could run you in problems one day - to have 2+ same-ID-elements

Upvotes: 0

James Montagne
James Montagne

Reputation: 78650

I looked for an insertBefore but apparently that doesn't exists in JavaScript.

You are using jquery which does have an insertBefore.

http://api.jquery.com/insertBefore/

function AddNewSystem(){    
    $('#template').clone().insertBefore('#cloned');
}

Upvotes: 1

Related Questions