With insertRow() method you can insert a new row at the specified position in HTML table. After row is created, use insertCell() method to insert a table cell. Wrap this methods in JavaScript functions and you have code to dynamically add new rows and columns in the HTML table. Please try to click the buttons below …
Small | ||
HTML | ||
table |
When you click the “Add row” button, appendRow() function is called. Function is simple, table row is inserted at the last position, and loop iterates through table cells in the first row. Why first row? Because you have to know the number of columns. For each step (cell in the first row), createCell() function creates and attaches DIV element to the newly created table cell.
// append row to the HTML table function appendRow() { var tbl = document.getElementById('my-table'), // table reference row = tbl.insertRow(tbl.rows.length), // append table row i; // insert table cells to the new row for (i = 0; i < tbl.rows[0].cells.length; i++) { createCell(row.insertCell(i), i, 'row'); } } // create DIV element and append to the table cell function createCell(cell, text, style) { var div = document.createElement('div'), // create DIV element txt = document.createTextNode(text); // create text node div.appendChild(txt); // append text node to the DIV div.setAttribute('class', style); // set DIV class attribute div.setAttribute('className', style); // set DIV class attribute for IE (?!) cell.appendChild(div); // append DIV to the table cell }
createCell() also sets class attribute (needed for the red and green background color) to the DIV element. It’ not necessary to create DIV element (you can append only text node to the TD element), but this is a good example of how to create and append new element to the table cell. appendColumn() is similar to the appendRow() function. For each table row, new cell is inserted to the last position in the row.
// append column to the HTML table function appendColumn() { var tbl = document.getElementById('my-table'), // table reference i; // open loop for each row and append cell for (i = 0; i < tbl.rows.length; i++) { createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col'); } }
Here is code used to delete table rows and columns (“Delete both” button, calls both functions).
// delete table rows with index greater then 0 function deleteRows() { var tbl = document.getElementById('my-table'), // table reference lastRow = tbl.rows.length - 1, // set the last row index i; // delete rows with index greater then 0 for (i = lastRow; i > 0; i--) { tbl.deleteRow(i); } } // delete table columns with index greater then 0 function deleteColumns() { var tbl = document.getElementById('my-table'), // table reference lastCol = tbl.rows[0].cells.length - 1, // set the last column index i, j; // delete cells with index greater then 0 (for each row) for (i = 0; i < tbl.rows.length; i++) { for (j = lastCol; j > 0; j--) { tbl.rows[i].deleteCell(j); } } }
Hi Dbunic,
Having an issue in the above said approach of setting name/id property for the newly created form element:
Issue
For eg. I have two rows in the form and values are already populated for the two rows and I’m adding a new row using AddRow function:
The newly created row is taking the reference of the all cells of the second row (index == 1) as below
Row1 (already populated)
<A></A>
Newly Added row (name is very similar to first row)
<A></A>
Can you please help.
Thanks,
Ramesh
Hey dbunic,
Your tips are really good. But, I have a doubt that i think it´s a little more complicated. I want to clone the table. And the table I wanna clone is inside another table, something like:
@Ramesh – It seems some HTML code is missing (I suppose that WordPress filtered your comment). Anyway, I prepared and sent offline example to you so we can continue discussion.
@Priscilla – every node in a DOM can be cloned. Please see the documentation for cloneNode method. Here is how DIV element is cloned in REDIPS.drag lib:
Cloned node will not be a part of the document until it is added to another node that is part of the document using appendChild or a similar method. If input parameter is set to true then children of the node will be also cloned.
very helpful – thanks!
OK , I have a quick question regarding Tables.
I am fairly new to JavaScript. taking evening classes. Now we have an excercise where we need to do the following:
– user will get prompted their age
– then it prompts them for the Gender
– now, depending on what they enter, I need to create a table that:
has rows and columns equal to the age entered and then the cells need to be filled with the male/female gender sign.
To be frank I have no idea how I am going to approach this.
I got the prompts and all working, but I am not able to apply that to the function.
@Zark – You can reuse appendRow() function from this post. With two loops and age as input parameter JS code will look like:
This code is a good enough to start with. Here is also simple HTML to use with JS code:
Legendary dbunic
I appreciate the prompt follow up!
Thank you
It works like a charm, with the age variable.
Now just one more question.
When I have the gender variable. How would I tell it to pupulate the cells with whatever I need to put in them?
@Zark – Here is modified function:
Just send age and gender variables to the function and all table cells will be populated with gender value.
Hi… this sees to really nice article… but a small problem …if u press it delete either rows or columns it deletes the complete rows & columns completely …. but if I need to delete a specific row of how to do it..
regards
Pravin Nair
Great drag and drop tools. I’ve been trying out all of your examples and they are impressive. I do have a question that I’m hoping you can help me out with. It seems that when I try to add more than 11 columns, the drag and drop becomes erratic in those farther columns. It seems that i can only go so far to the outer columns, drop it, and then try to move column by column until i get to the outermost column. Again don’t get me wrong, the tool is incredible, but wondering if you have a quick fix that will allow me to play with 15, 20 or 25 columns? Going down rows works flawlessly. If this problem can’t be fixed it’s stil one of the best tools I’ve come across.
Thanks in advance
@Pravin Nair – This post displays how to begin adding table rows and columns in JavaScript. Here are shown only basic functionality. I have also prepared small REDIPS.table library which contains merge/split cells and add/delete rows/columns methods. Please see REDIPS.table documentation with all contained features.
@Ron – REDIPS.drag should work nicely with really wide and long tables. Maybe the problem is due to DIV#drag dimensions. Please add the following style to the style.css file:
This will make DIV#drag visible. So, if DIV#drag is smaller than table, some columns may not work properly or will not be reachable at all. Just set correct width to the drag region and dragging should work fine. This problem is mentioned Appendix A documentation.
I’m way new to JavaScripts and figuring things out on my own – by reading a lot of online forums and such. I’m working with an online spreadsheet that automatically adds a row (with info) when a linked form is submitted. I have another sheet for which I’ve customized a script to pull certain columns from the source sheet. For some reason, the target sheet doesn’t has to have an equal number of rows as the source sheet for the script to work.
I’m trying to make the script compare the number of rows in each sheet and append any new rows if the target sheet is lacking, then run the script to pull the desired columns. I tried an if-else statement for the compare, but I get an error “cannot find method for appendRow()” – I don’t quite know how to fix that error. Can you help? The code is below:
Clarification – the target sheet HAS to have an equal number of rows for the script to work.
Got answers from a different forum. Disregard my comments. Thanks!
My guess is that open spreadsheets use HTML table as a base, so if you are familiar with tables then modification of such script should not be a problem. Anyway, I’m glad you found the answer. Cheers!
Hola si muy bueno este post me ayudo bastante, pero que pena tengo una pequeña inquietud me gustaria saber como puedo agregar en cada celda campos de texto, es decir a medida que se creen columnas con filas en las celdas se creen campos para luego ser insertados en una base de datos.
Agradezco la ayuda.
@Jenny – Hi, I don’t know Spanish so I used Google translator for your comment (sorry if your question was misunderstood). Anyway, if you want to append text fields in created rows / columns you can modify createCell() function like:
This function is called for every created table cell so you are free to customize it for your needs.
Can we add column in between??
Intention of this post is to show how is easy and simple manipulate HTML tables via JavaScript. Yes it’s possible to insert column instead of appending to table end. Please see my post Merge and split table cells with JavaScript where you will see complete functionality regarding adding/inserting table row/column. On the REDIPS.table documentation you will see how to define “index” for a new column (just search for column() method).
;)