7
\$\begingroup\$

Is it possible to create dynamic TR and TD elements in an HTML table? Something similar but better than this:

jQuery(document).ready(function() {
  $('button[name="new-title"]').on('click', function(){
    var table = $('table[name="errortitle"]');
    var tr = $('<tr />');
    var td = $('<td />');
    var input = $('<input />').attr({'class' : 'form-control'})
    var button = $('<button />').attr({'class' : 'btn'});
    var checkbox = input.clone().attr({'type' : 'checkbox', 'name' : 'check'});

    var tdId = td.clone().html('-');
    var tdTitle = td.clone().append(input.addClass('formInput').attr({'type': 'text'}));
    var tdCheckBox = td.clone().append(checkbox);
    var tdAction = td.clone().html(button.addClass('btn-danger').html('Usuń'));

    tr.append(tdCheckBox);
    tr.append(tdId);
    tr.append(tdTitle);
    tr.append(tdAction);

    table.append(tr);
  });
});

Is it possible to make this code nicer or more efficient?

\$\endgroup\$
2
  • \$\begingroup\$ An alternative way should be AngularJS. You can define a default HTML and ride a repeater into this code. For more information: AngularJS:ngRepeat \$\endgroup\$
    – Mephisto07
    Commented Jan 9, 2014 at 17:34
  • \$\begingroup\$ You can use insertRow and insertCell; very easy for tr and td. \$\endgroup\$ Commented Sep 8, 2018 at 19:47

1 Answer 1

9
\$\begingroup\$

You could create a function that will add a row to the table based on the number of elements of data you pass to it (which will become columns):

function newRow($table,cols){
    $row = $('<tr/>');
    for(i=0; i<cols.length; i++){
        $col = $('<td/>').append(cols[i]);
        $row.append($col);
    }
    $table.append($row);
}

You can then call this function for every new row you want to make. $table expects a jQuery object, cols expects an array of elements (DOM or jQuery) to append to the row. I've also tidied up the jQuery that creates your elements. Did you know you can use the second parameter in the jQuery function to set element properties?:

jQuery(document).ready(function() {
  $('button[name="new-title"]').on('click', function(){
    var table = $('table[name="errortitle"]');

    var tdId = '-';
    var tdTitle = $('<input />', {'class' : 'form-control formInput', 'type': 'text'});
    var tdCheckBox = $('<input />', {'class' : 'form-control', 'type' : 'checkbox', 'name' : 'check'});
    var tdAction = $('<button />', {'class' : 'btn btn-danger', html:'Usuń'});

    newRow(table,[tdCheckBox,tdId,tdTitle,tdAction]);
  });
});

JSFiddle

Try it with any amount of column data:

newRow(table,[tdCheckBox,tdId,tdTitle,tdAction,'another col','and another','a final col']);

JSFiddle

\$\endgroup\$
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.