Crayl
Crayl

Reputation: 1911

Javascript - removeChild removes a whole cell of a table

I have table where I can add new rows with input fields. Also there's a possibility to remove an added input field. Deleting a complete row works, but there's a problem to delete single input fields inside a cell. Here's the code:

cell1=document.getElementById('avz_tabelle').rows[par.rowIndex].cells;

var feld = document.createElement("input"); 
feld.setAttribute("name","avz_keywords" + avz_array + "[]"); 
feld.setAttribute("onblur","");
feld.setAttribute("type","text"); 
feld.setAttribute("size","30"); 
cell1[1].appendChild(feld);

var remove = document.createElement("a");
remove.setAttribute("href","#");
remove.setAttribute("onclick","this.parentNode.parentNode.removeChild(this.parentNode);");
remove.innerHTML = " X";
cell1[1].appendChild(remove);
var br = document.createElement("br");
cell1[1].appendChild(br);

The problem is that the remove action completly deletes the whole cell, instead of the related input field. The strange thing, that this works on the first tier of the table without problems. Do you see the error? Thanks for any suggestions!

Upvotes: 1

Views: 1547

Answers (2)

Mic
Mic

Reputation: 25164

Since you are building your HTML with the DOM, you don't have to set attributes for events:

replace remove.setAttribute("onclick"... by something like:

remove.onclick = function(ev){
  feld.parentNode.removeChild(feld);
}

feld and the onclick function are defined in the same scope, you have a closure here. It makes feld available inside the function.

Upvotes: 1

devnull69
devnull69

Reputation: 16564

Ok, you are appending the anchor element remove to cell1[1], which is a single table cell of the row with index par.rowIndex. So the parentNode to the anchor element is the cell. With this.parentNode.parentNode.removeChild(this.parentNode) you are removing the parentNode of the anchor, which is the cell.

EDIT: removed a sentence that might have been offensive ... sorry :-)

EDIT2: Possible solution:

this.previousSibling.parentNode.removeChild(this.previousSibling);

because this.previousSibling might be the input element

Upvotes: 1

Related Questions