Adding Table Rows on Button Click - javascript

I want to add table rows as the user clicks the Add button. In a new row there are 3 textboxes. As the rows gets added id of textboxes should be set like array list.
For e.g
if it is 2nd row added, the textbox ids will be textbox1_1 textbox2_1 textbox3_1
if it is 3rd row added, the textbox ids will be textbox1_2 textbox2_2 textbox3_2
Because I want to Add all these textboxes values in a single string at the end.
FIDDLE
Added later :-
Indeed at the first time there are no rows in the table.

try this:
$("#btnAdd").click(function(){
var id = $('table tr').size(),
i,
row = '<tr>';
for(i = 1; i <= 3; i++) {
row += '<td><input type="text" id="text'+i+'_'+id+'" />';
}
row += '</tr>';
$('table').append(row);
});
DEMO
Alternativly if you want to build from previous rows you can do this:
$("#btnAdd").click(function(){
var id = $('table tr').size(),
tr = $('table tr').last().clone();
$(tr).find('td').each(function (index) {
$(this).attr('id', 'text'+index+'_'+id);
});
$('table').append(tr);
});
DEMO

Try this : you can add row by cloning first row and updating each input's id by iterating them.
//get the count of available row in table
var count = $('#dynamicTable tr').length;
$("#btnAdd").click(function(){
//clone the first row in table
var $tr = $('#dynamicTable tr:first').clone();
//iterate each input to change its id
$tr.find('input').each(function(){
var id = $(this).attr('id');
id = id.substring(0,id.length-1);
$(this).attr('id',id+count);
});
// update count
count++;
//add row to the table
$('#dynamicTable').append($tr);
});
JSFiddle link

Try thus
$("#btnAdd").click(function(){
var rowCount = $("table tr").length;
var firstRow = $("table tr:first").clone();
firstRow.find("input").each(function(){
this.id=this.id.replace("_0","_"+rowCount);
});
$("table").append(firstRow);
});
DEMO

write less do more with jquery. use chaining as below
$("#btnAdd").click(function(){
$('table')
.find("tr:first") // traverse the first tr
.clone() // clone the row
.appendTo('table') // append the the table tag
.end() // reset to default selector
.find('input').each(function(i,x){
$(this).prop('id',this.id.split('_')[0]+'_'+(+$('table tr').length-1)); // assign the id to the added new row
});
});
EDIT done with FIDDLE too
Hope it helps....

Related

set id using setAttribute to td of last row of element

I am generating a table row which has two columns dynamically in html containing values from the database.
I want every td of the first column to have an unique id which i have done but i cant set the id to the td of last row in the table.
Here's the code to set id
<script>
var i=0;
var id=1;
while(i<100)
{
document.getElementsByTagName("td")[i].setAttribute("id", id);
i=i+2;
id=id+1;
}
</script>
Any help will be appreciated
but i cant set the id to the td of last row in the table.
You need to get to the last row in the table first.
var allRows = document.getElementsByTagName("tr");
var lastRow = allRows[allRows.length - 1];
now set Id to the first td of last row
lastRow.getElementsByTagName("td")[0].setAttribute("id" , allRows.length + 1 );
DOM Selectors are provided for a reason. :)
var tds = $('tr td:first-child');
var i=0;
$.each(tds, function(){
$(this).attr('id',i++);
});
OR
Using pure javascript
var tds = document.querySelectorAll('tr td:first-child');
var i = 0;
for(var td in tds){
tds[td].setAttribute('id',i++);
// or
//tds[td].id=(i++).toString();
};
You can use querySelectorAll to get all first td's withing given table using :first-child;
It will return NodeList which need to be convert into in an Array.
var arrTD = document.querySelectorAll("#list-notification tr td:first-child");
arrTD = Array.prototype.slice.call(arrTD);
var i =0;
arrTD.forEach(function(val,key){
val.setAttribute('id',i);
++i
})

jQuery DataTables clear table except the first row

I am using jquery datatables. I want to clear table except the first row.
var table = $('tableId').DataTable({});
Sample:
tr1
tr2
tr3
table.clear().draw(); //This clear all rows, How do I exclude first row
clear table:
tr1
How about this - I've used .rows().remove() instead of .clear(), so I could select which rows should be removed.
$('#deleteAll').click(function(){
//get first element
var firstElement = $('tbody > tr').first();
/*remove all <tr> which are coming after the first element and
redraw the table */
table.rows(firstElement.nextAll('tr')).remove().draw();
});
Fiddle

Jquery/Javascript | HTML Table Sum Total Records of sibling TD in last TD

I am Trying to Update the Last based on the sum of sibling in that row..
The Table TD has class contenteditable = "TRUE" when clicked.
so i am trying when someone try to update the digit on that td column it should also update the last in that row.
Here is the Fiddle of the Table i have now..
JS FIDDLE LINK HERE
You need to add keyup() event for .inner class like,
$('tr.tableRow td.inner').on('keyup',function(){
$tr=$(this).closest('tr');
var sum=0;
$tr.find('td.inner:not(.total)').each(function(){
sum += Number($(this).text());
});
$tr.find('.total').text(sum);
});
Also in my demo I added a class .total to show the total of all inner class. See the Live demo
You can calculate on blur of edited TD
$('tr.tableRow td.inner').on('blur',function(e){
var sumTD = $(this).parent().find("td:last");
sumTD.text(parseInt(sumTD.text())+ parseInt($(this).text()));
});
http://jsfiddle.net/yhjw23of/9/
check your js fiddle link
$('tr.tableRow td.inner').on('click',function(e){
e.preventDefault();
e.stopImmediatePropagation();
$(this).attr('contentEditable','true');
$(this).addClass('inputCopyCat');
$(this).focus();
});
$('tr.tableRow td.inner').focusout(function(e){
$('td.inputCopyCat').removeAttr('contentEditable');
$('td.inputCopyCat').removeClass('inputCopyCat');
var currentTableRow = $(this).parent();
var currentTabelRowSum = 0;
currentTableRow.find('td.inner:not(:last)').each(function() {
var userInput = parseInt(this.innerText);
if(!isNaN(userInput)) {
currentTabelRowSum += parseInt(this.innerText);
}
});
currentTableRow.find('td.inner:last').text(currentTabelRowSum);
});

Inserting row number in the table while appending new row

I am trying to append new row in my table with row number but this is not working.
$('.dropdown-menu li a:eq(8)').on('click', function(){
rows='';
var myRow =(this).rowIndex;
var row='<tr><td>'+myRow+'</td><td></td><td></td><td></td><td></td><td></td></tr>';
rows=rows+row;
$(rows).appendTo('table');
});
It is returning undefind in place of row number.
Try this:
$('.dropdown-menu li a:eq(8)').on('click', function(){
var rows='<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>';
$(rows).appendTo('table');
$('table tr:last td:first-child').text(parseInt($('table tr').length)-1); // Minus 1 because index starts from 0.
});

clone table row, append random or sequential number to ID

So i have this code
$('input.clone').live('click', function(){
//put jquery this context into a var
var $btn = $(this);
//use .closest() to navigate from the buttno to the closest row and clone it
var $clonedRow = $btn.closest('tr').clone();
//append the cloned row to end of the table
//clean ids if you need to
$clonedRow.find('*').andSelf().filter('[id]').each( function(){
//clear id or change to something else
this.id += '_clone';
});
//finally append new row to end of table
$btn.closest('tbody').append( $clonedRow );
});
Problem is, each row i clone gets named whatever _clone
How would i write this so that each time i run the function, it picks either a random or more idealy sequential number to append to the id isntead of "_clone"
String(Math.floor(Math.random()*1000000))
will give you a random number in string form between 0 and 999999.
Why not use the count of rows in the table
$clonedRow.find('*').andSelf().filter('[id]').each( function(){
//clear id or change to something else
var rowCount = $btn.closest('tr').siblings().length;
this.id += 'row_' + rowCount;
});
$('input.clone').live('click', function(){
var $btn = $(this);
var $clonedRow = $btn.closest('tr').clone();
$clonedRow.find('*').andSelf().filter('[id]').each( function(){
this.id += '_clone' + $(this).siblings().size();
});
//finally append new row to end of table
$btn.closest('tbody').append( $clonedRow );
});

Categories

Resources