Tuesday, June 13, 2006

Dynamic HTML Forms Code Snippet

I'm sure that there are a lot of examples in the Internet of how to implement it so I'm just paste my own snippet "as is" without any explanation of how its works.

Copy-Paste it to see how it works.


<html>
<head>
<script type="text/javascript">
var id = 0;

function addElement(container) {
id++;

var htmlId = "id" + id;

container.innerHTML += "\n<div id=\"" + htmlId + "\">"
+ "\n I'm number " + id
+ "\n <button onclick=\"removeElement('" + htmlId + "')\">Remove</button>"
+ "\n</div>";
}

function initContainer() {
addElement(document.getElementById("container"));
}

function removeElement(id) {
document.getElementById("container").removeChild(document.getElementById(id));
}
</script>
</head>
<body>
<form id="container">
<script type="text/javascript"> initContainer(); </script>
</form>
<button onclick="addElement(document.getElementById('container'))">Add</button>
</body>
</html>


More Information
Dynamic Content with DOM-2