0

I have the following code.

arrayToTable = function(data, options = {}){
    var table = $('<table />'),
        thead,
        tfoot,
        rows = [],
        row,
        i, j,
        defaults = {
            th: true, // should we use th elemenst for the first row
            thead: false, //should we incldue a thead element with the first row
            tfoot: false, // should we include a tfoot element with the last row
            attrs: {} // attributes for the table element, can be used to
        }

    options = $.extend(defaults, options);

    table.attr(options.attrs)

    // loop through all the rows, we will deal with tfoot and thead later
    for(i = 0; i < data.length; i++){
        row = $('<tr />');
        for(j = 0; j < data[i].length; j++){
            if(i == 0 && options.th){
                row.append($('<th />').html(data[i][j]));
            }else{
                row.append($('<td />').html("<input type='text' name='fname'>"));
            }
        }
        rows.push(row);
    }

    // if we want a thead use shift to get it
    if(options.thead){
        thead = rows.shift();
        thead = $('<thead />').append(thead);
        table.append(thead);
    }

    // if we want a tfoot then pop it off for later use
    if(options.tfoot){
        tfoot = rows.pop();
    }

    // add all the rows
    for (i = 0; i < rows.length; i++) {
        table.append(rows[i]);
    };

    // and finally add the footer if needed
    if(options.tfoot){
        tfoot = $('<tfoot />').append(tfoot);
        table.append(tfoot);
    }
    return table;
}

    var data = [
        ['Name', 'Age', 'Email'],
        ['John Doe', '27', '[email protected]'],
        ['Jane Doe', '29', '[email protected]']
    ];

    var table = arrayToTable(data, {
        thead: true,
        attrs: {class: 'table'}
    })

    $('body').append(table);

and it produces this:

http://jsfiddle.net/bytg16k6/

I need a button to dinamycally add new rows to it, but I am stuck with that

1 Answer 1

2

You table has a class (can have an id if you have multiple tables with this class), then you can use the following code on click of a button with class 'add-row':

$('.add-row').on('click', function () {
    $('.table').append('<tr><td>test</td><td>test</td><td>test</td></tr>');
  });

http://jsfiddle.net/bytg16k6/1/

Please note the above code is just an example of a way to do this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.