illichosky
illichosky

Reputation: 157

Add and removing rows [with input field] in a table

I'm a total javascript noobie. I developed the code bellow following and modifing some random tutorial I found. It should add and remove rows with input fields at a table, however, it does nothing. It also worth saying that I called the function as a link. I added 'javascript:addRow()' inside the tag and at the header. Did I missed something?

function addRow(){

tableID="ticketCreate";
var table = document.getElementById(tableID);
var rowCount = table.rows.length;

if(rowCount<7){

    var row = table.insertRow(rowCount);

    var cel1=row.insertCell(0);
    var element1= document.createElement("input");
    var element1.type="text";
    cell1.appendChild(element1);

    var cell2=row.insertCell(1);
    var element2.type="text";
    cell1.appendChild(element2);

    var cell2=row.insertCell(2);
    var element3.type="text";
    cell1.appendChild(element3);

    rowCount++;

}

}

function removeRow(){

    tableID="ticketCreate";
var table = document.getElementById(tableID);
var rowCount = table.rows.length;

if(rowCount>1){
    table.deletRow(rowCount);
    rowCount--;
    }


}

Upvotes: 2

Views: 7020

Answers (2)

Tim
Tim

Reputation: 2440

The error is here:

var element1= document.createElement("input");
var element1.type="text";

It should be

var element1= document.createElement("input");
element1.type="text";

and similar for the other elements.

You declare the variable with

var element1 = 'something';

and then access it with

element1 = 'something different';

Also there is a typo in

var cel1=row.insertCell(0);

It needs to be

var cell1=row.insertCell(0);

Additionally you did not define element 2 and 3, used cell2 twice where it should be cell2 and cell3 and only appended to cell1.

Upvotes: 0

mrtsherman
mrtsherman

Reputation: 39872

You have several errors, but here is the basic working model. I think you should be able to sort it out from here

http://jsfiddle.net/dBzkX/

function addRow() {

    var tableID="ticketCreate";
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    if(rowCount<7){
        //You declared var in front of the same variable twice. Don't do that.
        //You were appending cells inside existing cell. Add them to row instead.
        var row = table.insertRow(rowCount);
        var cell1 = row.insertCell(0);
        var element1 = document.createElement('input');
        element1.type="text";
        cell1.appendChild(element1);
        row.insertCell(1);
        row.insertCell(2);
    }
}

function removeRow(){
    var tableID="ticketCreate";
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    if(rowCount>1){   
        //you had type in deletRow. Also, you can pass in -1 to remove the last row        
        table.deleteRow(-1); 
    }
}

Upvotes: 1

Related Questions