I am trying to dynamically add and remove text fields using javascript and HTML. I can add and remove it, but sometimes the delete button does not work. when I check the item, it says that there is no onclick value for the delete button. I do not understand why, when I set onclick in the add function.
Here is my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
source
share