I have the following code that adds a file upload option to a div and will remove the last element added.
<script language="javascript" type="text/javascript">
function add(type) {
var element = document.createElement("input");
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
element.setAttribute("style", "width: 500px;");
var newfile = document.getElementById("uploadhere");
newfile.appendChild(element);
}
function remove() {
var newfile = document.getElementById("uploadhere");
newfile.removeChild(newfile.lastChild);
}
</script>
I am trying to figure out a way to remove a specific element added instead of just removing the last element probably with an index somehow. Or even just having a remove button next to the element created.
edited to add my solution
This is how I solved the issue
<script language="javascript" type="text/javascript">
var i = 0;
function add(type) {
var element = document.createElement("input");
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
element.setAttribute("style", "width: 500px;");
element.setAttribute("id", "element-" + i);
var removebutton = document.createElement("input");
removebutton.type = "button";
removebutton.value = "Remove";
removebutton.setAttribute("id", "remove-" + i);
removebutton.setAttribute("onclick", "remove(" + i + ")");
var newfile = document.getElementById("uploadhere");
newfile.appendChild(element);
newfile.appendChild(removebutton);
i++;
}
function remove(id) {
document.getElementById("uploadhere").removeChild(document.getElementById("element-" + id));
document.getElementById("uploadhere").removeChild(document.getElementById("remove-" + id));
}
</script>