Question

I'm trying to create to remove a form element using javascript. When I remove an element, it removes the topmost element. I'm trying to remove a specific element. Here is a link to the page and below is the code. Any help would be appreciated, thanks! http://training.cvrc.virginia.edu/test.html

<script type="text/javascript">
var patient = 0;
function add_patient() {
patient++;
   var add= document.createElement('patientdiv');
   add.innerHTML += "<div id=removepatient></br>Patient "+patient+" Name/ID:<input type=text name=patients[] ><input type=button id=more_fields onclick=removepatient(); value='Remove' ></div>";
   document.getElementById('patientdiv').appendChild(add);
   return false;
}

function removepatient() {
    var elem = document.getElementById('removepatient');
   elem.parentNode.removeChild(elem);
   return false;
}
</script>


<div id=patientdiv></div>
<input type=button id=more_fields onclick=add_patient(); value='Add Patient'></br></br>
Was it helpful?

Solution

You should generate a unique ID for each element you are adding to the page. You can use a variable and increment this variable each time an element is added. In your exemple, the variable 'patient' is enough.

add.innerHTML += "<div id=removepatient_"+patient"></br>Patient "+patient+" Name/ID:<input type=text name=patients[] ><input type=button id=more_fields"+patient+" onclick=removepatient("+patient+"); value='Remove' ></div>";

You must also add a param to your delete function :

function removepatient(patient) {
    var elem = document.getElementById('removepatient_'+patient);
   elem.parentNode.removeChild(elem);
   return false;
}

I hope it helps you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top