JSFiddle - React, Tailwind, and code Playground
by Dimitar Christoff
HTML
<a href="#" id="add">add</a> | <a href="#" id="remove">remove last</a>
<div id="new_field"></div>
JavaScript
var inputs = {
fields: 0,
target: "new_field",
addInput: function() {
if (this.fields != 10) {
this.fields++;
var newElement = document.createElement('div');
newElement.id = this.target + this.fields;
newElement.innerHTML = " <input type='text' name='friends[]' value='' size='auto' maxlength='45' /> <a href='#' onclick='inputs.removeInput(" + this.fields + ");return false'>del</a><br />";
document.getElementById(this.target).appendChild(newElement);
} else {
alert("Only 10 fields allowed.");
// document.form.add.disabled = true;
}
},
removeInput: function(index) {
index = index || this.fields; // either a particular one or last one
var fieldToRemove = document.getElementById(this.target + index);
if (!fieldToRemove) return;
fieldToRemove.innerHTML = ''; // empty it to avoid memory leaks.
fieldToRemove.parentNode.removeChild(fieldToRemove);
this.fields--;
}
};
// attach events
window.onload = function() {
document.getElementById("add").onclick = function() {
inputs.addInput();
return false;
};
document.getElementById("remove").onclick = function() {
inputs.removeInput();
return false;
};
};