Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a table with rows that can be copied (adding a new row after that one, containing the same) with Javascript?

I am trying to make a table containing several rows, each with a button in the last cell that creates a copy of the row.

All the other cells contains an input (text). The content (value) of the inputs that are added must be the same as the one above (the one they are copies of).

The copies cannot be copied however!


The inputs must have a unique name something like this:
1-1-name
1-1-age
1-1-country
1-1-email

and if this row is copied, the copied inputs must have names like this
1-2-name
1-2-age
1-2-country
1-2-email

The next one with 3 instead of 2, and so on.


The problem with this, I guess, is that I must do this without JQuery. I can only use Javascript. Is this even possible?

like image 421
Levi Avatar asked Oct 05 '22 17:10

Levi


1 Answers

Take a look at this fiddle. Here is a pure js (no-jQuery) way to duplicate a table row and increment it's ID:

var idInit;
var table = document.getElementById('theTable');
    table.addEventListener('click', duplicateRow);  // Make the table listen to "Click" events

function duplicateRow(e){
    if(e.target.type == "button"){ // "If a button was clicked"
        var row = e.target.parentElement.parentElement; // Get the row
        var newRow = row.cloneNode(true); // Clone the row

        incrementId(newRow); // Increment the row's ID
        var cells = newRow.cells;
        for(var i = 0; i < cells.length; i++){
            incrementId(cells[i]); // Increment the cells' IDs
        }
        insertAfter(row, newRow); // Insert the row at the right position
        idInit++;
    }
}

function incrementId(elem){
    idParts = elem.id.split('-'); // Cut up the element's ID to get the second part.
    idInit ? idParts[1] = idInit + 1 : idInit = idParts[1]++;  // Increment the ID, and set a temp variable to keep track of the id's.
    elem.id = idParts.join('-'); // Set the new id to the element.
}

function insertAfter(after, newNode){
    after.parentNode.insertBefore(newNode, after.nextSibling);
}​
<table id="theTable">
    <tr id="1-1">
        <td id="1-1-name"><input type="text"/></td>
        <td id="1-1-age"><input type="text"/></td>
        <td id="1-1-country"><input type="text"/></td>
        <td id="1-1-email"><input type="text"/></td>
        <td id="1-1-button"><input type="button" value="Copy"/></td>
    </tr>
</table>​

Edit: Updated to insert the new row after the clicked one. Now with buttons and inputs!

like image 162
Cerbrus Avatar answered Oct 10 '22 01:10

Cerbrus