set id using setAttribute to td of last row of element - javascript

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
})

Related

Add class name to appended child elements with jquery

I have a table like this.
<table id='table1'>
</table>
and in this table i am dynamically adding rows to the table using jquery like below.
var tbl = $("#table1");
tbl.append('<tr></tr><tr></tr><tr></tr>');
I can add class to the appended rows using 2 methods like below
case 1
tbl.find('tr').eq(0).addClass("test");
tbl.find('tr').eq(1).addClass("test");
or case 2
for (var i=0;i<tbl.find('tr').length;i++) {
tbl.find('tr').eq(i).addClass("test")
}
and my question is there any way i can add same classname to the dynamically appended rows. Answers expecting in jquery. Thanks in advance.
Once an element is added to the DOM, you have no way of telling if it was dynamically added or not unless you have custom code that does such. I would suggest changing .append to .appendTo so you have access to the rows you're adding and can call .addClass:
var tbl = $("#table1");
$('<tr></tr><tr></tr><tr></tr>').appendTo(tbl).addClass("test")
You could also put the class in the string then append it or modify it (add a class) prior to appending it. Note how I only have one tr in my string but append it multiple times (optionally adding a class as noted)
var tbl = $("#table1");
var tr = '<tr class="test"></tr>';
var td = '<td class="test">new data</td>';
//var addedrow = $(tr).append(td).addClass("newclass");//adds class to the row
var addedrow = $(tr).append(td);//create new row object
addedrow.find('td').addClass("newclass"); //adds class to the td in the new row
var ar2 = $(tr).append(td);
var ar3 = $(tr).append(td);
tbl.append(addedrow, [ar2, ar3]); // appends the new rows
tbl.find('tr').last(td).addClass("newclass");//add class to last rows td
see it in action here: http://jsfiddle.net/MarkSchultheiss/0osLfef3/

Adding Table Rows on Button Click

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....

Go step by step through the html table

I need to insert some value into html table dynamically. For example, I have some inputs and then I have a table (about 5 rows), so I have one button which enables a timer. When the timer is stopped I need to insert data into table.
Here is the code, how do I add data to one row?
document.getElementById('d1').innerHTML = document.getElementById('ctrl_ball_size_val').value;
document.getElementById('l1').innerHTML = document.getElementById('ctrl_cilindr_height_val').value;
document.getElementById('t1').innerHTML = document.getElementById('stopwatch').value;
How can I add data (data can be different) to the table row by row?
It is highly recommended to avoid using innerHTML for this task.
I suggest to use the DOM to achieve that.
Here is a quick example on how you can create HTML table dynamically using JavaScript:
var tbl = document.createElement("table");
for(var i=0;i<=10;i++){
var tr = document.createElement("tr");
for(var j=0;j<=10;j++){
var td = document.createElement("td");
td.innerHTML = i*j;
tr.appendChild(td);
}
tbl.appendChild(tr);
}
document.body.appendChild(tbl);
Check out my Live example
If you are using JQuery Simply use:
$('#tableID > tbody > tr').each(function() { //Acess $(this) });
And you Never Need it then?
as per jQuery each loop in table row, just a bit of code:
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}

jQuery: Get next table cell vertically

How can I use jQuery to access the cell (td) immediately below a given cell in a traditional grid-layout html table (i.e., one in which all cells span exactly one row and column)?
I know that the following will set nextCell to the cell to the immediate right of the clicked cell because they are immediate siblings, but I am trying to retrieve the cell immediately below the clicked cell:
$('td').click(function () {
var nextCell = $(this).next('td');
});
Preferably I would like to do it without any use of classes or ids.
Try this:
$("td").click(function(){
// cache $(this);
var $this = $(this);
// First, get the index of the td.
var cellIndex = $this.index();
// next, get the cell in the next row that has
// the same index.
$this.closest('tr').next().children().eq(cellIndex).doSomething();
});
$('td').click(function () {
var index = $(this).prevAll().length
var cellBelow = $(this).parent().next('tr').children('td:nth-child(' + (index + 1) + ')')
});
index is the 0-based index of the cell in the current row (prevAll finds all the cells before this one).
Then in the next row, we find the nth-child td at index + 1 (nth-child starts at 1, hence the + 1).
How about:
$('td').click(function () {
var nextCell = $(this).parent().next().find("td:nth-child(whatever)");
});
If you want to do it without using selectors, you can do:
function getNextCellVertically(htmlCell){
//find position of this cell..
var $row = $(htmlCell).parent();
var cellIndex = $.inArray(htmlCell, $row[0].cells);
var table = $row.parent()[0];
var rowIndex = $.inArray($row[0], table.rows);
//get the next cell vertically..
return (rowIndex < table.rows.length-1) ?
table.rows[rowIndex+1].cells[cellIndex] : undefined;
}
$('td').click(function () {
var nextCell = getNextCellVertically(htmlCell);
//...
});
Not that efficiency is important here but it works out much faster to do it like this - in tests over 100,000 iterations it was 2-5 times faster than the selector based approaches.
Are there an equal number of cells in each table row? If so, you could get the "count" of the cell in question, then select the corresponding cell in the next('tr').

HTML how to move through columns

I have the following code:
$(document).ready(function() {
var id = 'cbx';
var idPrefix = 'Arrow';
var html = '<img .../>';
// query parent row
var rowq = $('#' + id);
if (rowq.length < 1) {
rowq = $('.' + id);
VersionHeader = true;
}
if (rowq[0]) {
rowq.addClass('ArrowHeader');
// set to 0 for header
var index = 0;
var row = rowq.parents('.g')[0].insertRow(index);
// assign id for new row
row.id = idPrefix + id;
// assign classes for style and tree
row.className = 'srcrow' + id;
// insert new cell
var cell = row.insertCell(0);
// assign html result
cell.innerHTML = html;
// set colspan
cell.colSpan = 1;
Now my problem is it adds the cell but it adds it under the first column. Is there a way to move through the columns? Granted I'm not an html expert at all. Just a beginner trying to get some stuff to work and would appreciate some help since I'm totally lost. I didn't include the html just ... through it.
Thanks
I'm not sure I'm understanding your question entirely correctly (I gather you are attempting to insert a cell into a new row, and you want to select into which column it is inserted?). Assuming that's what you meant:
row.insertCell(0)
This is your problem. The insertCell method takes as an argument the index of the column into which the cell should be inserted. Index 0 is the first column, index 1 is the second column, and so on. So try replacing the 0 with the appropriate index.

Categories

Resources