I’m trying to dynamically add and remove textboxes with a click of a button. The add() works but the remove() does not.
$ctra = 1;
function add() {
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = "<table><tr><td width=159> Name</td>"+
"<td> <input type='text' name='name' size=20> </td>"+
"<td> Address </td>"+
"<td> <input type='text' name='address' size=20> </td>"+
"<td> Tel. No </td>"+
"<td> <input type='text' name='telno' size=20><td> <button type='button' onclick='remove(divIdName);'>Remove</button></table>";
if($ctra<5){
ni.appendChild(newdiv);
$ctra++;
}
$total = $ctra;
}
This is the remove(). It accepts the name of the div.
function remove(dId) {
var ni = document.getElementById('myDiv');
ni.removeChild(dId);
}
Please help me fix the problem. Thank you!
You need to change the onclick to be the following:
and then call the remove function like so
here is a jsfiddle of it working: http://jsfiddle.net/JFzCf/5/