Add html element jQuery
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_开发者_如何学Goadder").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.
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/.
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/
精彩评论