Dynamically add HTML- elements using Javascript

Ever wanted to dynamically add HTML- form elements to your website? For example, if you want to have the ability to assemble your own list of items?

This script might help you to do so. It is extensible to add other elements as just normal input- fields.

After integrating it to your site, the whole thing might look like this:

You can add new input fields with the [+] button and remove existing inputs with [-]

Currently running flawlessly with Mozilla Firefox. Internet Explorer causes problems.


<html>
<head>
<title>JS HTML Element adder (w. OOP)</title>
<script language='JavaScript' type='text/javascript'>

function FormInput(name) {
	this.name = name;
	// window[name] = this;
	this.FormInput = new Array(0);
	this.FormInputValue = new Array(0);

	document.write("<p id='" + this.name + "'></p>")
	document.write("<a href='javascript:" + this.name + ".addFormInput()'>[+]
		</a>&nbsp;<a href='javascript:" + this.name + ".removeFormInput()'>
		[-]</a>");

	this.addFormInput=function() {
		this.FormInput.push(this.FormInput.length);
		this.FormInputValue.push("");
		this.createFormInput();
	}

	this.createFormInput=function() {
		document.getElementById(this.name).innerHTML="";
		for (i=0; i<this.FormInput.length; i++) {
			document.getElementById(this.name).innerHTML+=
			this.displayFormInput(this.FormInput[i],
			this.FormInputValue[i]);
		}
	}

	this.saveFormInputValue=function(id, value) {
		this.FormInputValue[id]=value;
	}

	this.displayFormInput=function(id, value) {
		return this.name + id + "&nbsp;
		<input type='text' " + this.name + "='" + id + "'
		onchange='javascript:" + this.name + ".saveFormInputValue(
		" + id + ", this.value)' value='" + value + "'><br>";
	}

	this.removeFormInput=function() {
		if (this.FormInput.length > 0) {
			this.FormInput.pop();
			this.FormInputValue.pop();
		}
		this.createFormInput();
	}
}

</script>
</head>
<body>
<form name="test">
<script language='JavaScript' type='text/javascript'>

testing = new FormInput('testing');
testing2 = new FormInput('testing2');

</script>
</form>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*