There are a huge number of different ways to do this. I recently had a project where I had to do this very thing. Here is a working Fiddle of the following code example:
HTML
<div id="container">
<span id="sholder"></span>
<br />
<input type="button" value="Add Section" class="addsection" />
</div>
<div id="section_template" class="template">
<div class="section">
<span class="taholder"></span>
<br />
<input type="button" value="Add Textarea" class="addtextarea" />
</div>
</div>
The key concept here is that I created a div
section with class template
, and in the CSS template
is set to display: none;
. I use it to more easily create a bigger section of HTML later in the CreateSection()
function.
jQuery / javascript
$(function() {
//add the click handler to add a new section
$("input.addsection").click(CreateSection);
//add the click handler for the new section
//since the buttons are added dynamically, use "on" on the "document" element
// with the selector for the button we want to watch for.
$(document).on("click", "input.addtextarea", function() {
var section = $(this).closest("div.section");
AddTextarea(section);
});
});
function CreateSection() {
var section = $("#section_template div.section").clone();
var holder = $("#container span#sholder");
//get the current total number of sections
var sectionCount = holder.find("div.section").length;
//create the section id by incrementing the section count
section.attr("id", "section" + (sectionCount + 1));
//add a textarea to the section
AddTextarea(section);
//add the new section to the document
holder.append(section);
}
function AddTextarea(section) {
var sectionID = section.attr("id");
var holder = section.find("span.taholder");
//get the current total number of textareas in this section
var taCount = holder.find("textarea").length;
//create the new textarea element
var ta = $(document.createElement("textarea"));
//create the textarea unique id
var taID = section.attr("id") + "_textarea" + (taCount + 1);
ta.attr("id", taID);
//show the id... can be removed
ta.val("ID: " + taID);
//add the textarea to the section
holder.append(ta);
}
There are several helpful search functions in the above code: closest, find. Also, I'm using the clone function to duplicate that HTML section.
Also of note, I create the new textarea
using $(document.createElement("textarea"))
. document.createElement
is the fastest way for JS to create new HTML DOM objects.
And a bit of CSS for the example
div.template {
display: none;
}
div.section {
border: 1px solid black;
}
div.section textarea {
display: block;
}
This example keeps the IDs unique as you can see in the JSFiddle. However, reading those fields if they are posted to the server is an answer to another question.