I don't know if anyone else would ever need or want something like this, but here we go. If you want to be able to create multiple forms on demand on the same page along with maintaining the ability to remove them or interact with them, then this is for you. First thing first, we need to make an HTML document.
<!DOCTYPE html>
<html>
<head>
<title>Some Stupid Form Thing</title>
Now let's get our Javascript on! I know I add some stuff that is not needed, but I'm weird.
<script type="application/javascript">//<[CDATA[
"use strict";
//I like to do a global storage object
var storage = {
"formdata": "",
"fid": 1
}
// function to store original form setup
function getformdata() {
storage["formdata"] = document.getElementById("form0").innerHTML;
}
//Creating new forms
function addform() {
var newform = document.createElement("form");
newform.id = "form" + storage["fid"]++;
newform.innerHTML = storage["formdata"];
document.getElementById("formlist").append(newform);
}
// Removing forms, or reset the last form
function removeform(b) {
b.parentElement.remove();
if (document.getElementById("formlist").children.length < 1) {
storage["fid"] = 0;
addform();
}
}
//]]></script>
</head>
Now that all the delicious code is out of the way, we need to create the body that this will interact with. It's actually fairly simple.
<body onload="getformdata()">
<div id="formlist">
<form id="form0" action="#">
Employee ID: <input type="text" value="" class="eid" /><button type="button">Do a thing</button><br />
<button type="button" onclick="removeform(this)">Remove</button>
/form>
</div>
<button onclick="addform()">Add Form</button>
</body>
</html>
Summary time. I am using a div as a container to create and remove forms in. Using the DOM we can isolate what we need inside of whatever container and use that to modify whatever with minimal navigation, no extra overhead of frameworks needed. I don't know why anyone would need this, other than the reason I made it that I'm not going to say. But there you go.
No comments:
Post a Comment