0

I'm trying to copy a textarea in my html code by clicking a button that adds it to the same container of the first textarea.

My code is:

$("#note_adder").click(function(){$("#p_note").clone().append('note_id')});
  • Button's id is note_adder
  • Textarea's id is p_note
  • Container's id is note_id

I also want to change the name attribute of the newly created textarea.

2 Answers 2

7

Two things: you need to use appendTo, and you need a # in front of note_id.

$('#note_adder').click(function () {
    var counter = $('[id^="p_note"]').length;
    $('#p_note').clone().attr({
        id: 'p_note_' + counter,
        name: 'p_note_' + counter
    }).appendTo('#note_id');
});

I also changed the id of the cloned textarea since IDs should be unique. With each successive click, it should produce new textareas with names and ids of:

  • p_note_1
  • p_note_2
  • etc...

Here's a demo borrowed from Shadow Wizard's answer: http://jsfiddle.net/cq9Hq/2/.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for suggesting to change the ID, but what when button clicked twice? :)
@Shadow, aha good point! Let me work on it... How is that now?
Simple matter of counter.. feel free to use my below test case. :)
3

Need to be appendTo:

$("#note_adder").click(function(){$("#p_note").clone().appendTo('#note_id')});

Live test case: http://jsfiddle.net/cq9Hq/

Updated with Box9 better approach: http://jsfiddle.net/cq9Hq/1/

2 Comments

thanks for mentioning the appendTo mistake i didn't notice it and for live test :)
@Star cheers, as Box9 answer is the same as mine and better (same ID is really bad idea) the only reason I leave my answer is for the test case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.