Fragmented Thought

jQuery Table Auto Row

By

Published:

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

Another one mostly for myself, part of a larger picture I'm putting together. This small little javascript object will make it so any table you add a class of "auto-row" will have fun new behaviors. When any select, input, or textarea element in the last row changes, the row is duplicated and added right below. All digits in patterns "like" [##]" are automatically incremented for you before they are attached to the DOM. The row you were editing looses it's special behavior, and the newly inserted row is prepared to do the same. Inserted rows have the selects changed to the first option, text fields emptied, and checkboxes unchecked. Hidden fields are not altered.

Code updated 11/3/2010.

This jquery script uses the .live() function, and requires at least jQuery 1.3 or higher.

autoRowTable : { init: function(){ // This could be a table, thead, tbody, or tfoot $('table.auto-row').each(function(){ $(this).find('tr:last input, tr:last select, tr:last textarea').live('change', function(){ trialManagers.autoRowTable.elementChanged(this); }); }); } ,elementChanged: function(element){ var elementRow = $(element).parents('tr'); elementRow.children('input, select, textarea').unbind('change'); var clone = elementRow.clone(); // Increment anything in the html that follows a pattern like: _[##]" or _##" var cloneHTML = clone.html(); var regex = /(\[)(\d+)(\])/img; var matches = []; var match; match = regex.exec(cloneHTML); while( match instanceof Array ){ if(!matches[match[2]]){ matches[match[2]] = match; } match = regex.exec(cloneHTML); } matches.sort(function(a,b){return a - b}).reverse(); // Work highest down or you increment all the way up console.log(matches); $.each(matches, function(index, match){ if( match instanceof Array ){ re = new RegExp('\\[' + match[2].replace('/', '') + '\\]', 'img'); cloneHTML = cloneHTML.replace(re, '[' + ((match[2]-0)+1) + ']'); } }); clone.html(cloneHTML); clone.toggleClass('even').toggleClass('odd'); clone.find('input:text, textarea').val(''); clone.find('input:checkbox').removeAttr("checked"); clone.find('select option:first').attr('selected', 'selected'); /* clone.find('input, select, textarea').each(function(){ //Further customization if you need. }); */ elementRow.after(clone); } }