how to get the id of a tr inside the loop - javascript

hi i got the tr content like this way simil
var td = $("tr td"); // get first child of all the td elements
var htmlContent = []; // initilize an empty array
for (i = 0; i < td.length; i++) {
htmlContent[i] = $(td[i]).text();
trid[i] = $(td[i]).attr("id");
}
i want the tr id so i use this code
trid[i] = $(td[i]).attr("id");
but this is not good

You can use .parent() to get the tr, and then its id.
var htmlContent = []; // initilize an empty array
$('tr td').each(function () {
htmlContent.push($(this).text());
console.log($(this).parent().attr('id'));
});
Here is a simple fiddle: https://jsfiddle.net/hxsbLws2/1/

You should use td only since it is already a DOM object. You don't need to use it as a selector again like this $(td) ..
Then just specify the index td[i]
trid[i] = td[i].attr('id');

Related

Selecting a table data using javascript/jquery

Hi i am new to javascript and jquery.I just like to know if there is any way of selecting a table data using this format:
$("#myTable").row[index1][index2];
where index1 is row index, index2 is column. Anything similar is fine too.
Try this : you can use .eq() in jQuery to traverse through tr and td with specified index
var td = $("#myTable").find('tr:eq('+index1+')').find('td:eq('+index2+')');
var data = $(td).text();// you can use .html() if you need html inside td
Try This:
$(function(){
$('input').click(function()
{
var t= $(this).attr('class');
var text= $('.time'+t).text();
alert(text);
});
$('td').click(function()
{
var index = this.cellIndex;
alert($('tr:first').find('td').eq(index).text());
});
});
http://jsfiddle.net/oL4pfgda/
It will iterate your table cells and print the values-
$("#myTable>tr>td").each(function () {
var cell_value = $(this).html();
alert(cell_value);
})

looping javascript didn't work

I'm trying to get data from app engine datastore using javascript and json. it's also allowed jsonp service, here the javascript code:
$.getJSON("http://1.handy-post-402.appspot.com/show?callback=?", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.isi;
var user = map.No_HP;
var date = map.tanggal;
$('#date').text(date);
$('#nohp').text(user);
$('#content').text(content);
}
});
you can also check it here: http://jsfiddle.net/YYTkK/7/
unfortunately, it just retrieve 1 latest data from the datastore. am I doing something wrong with this code?
thanks in advance.
You're not appending elements, but simply changing the value of the same 3 elements in question three times. So you simply overwrite the value you put into it the time before. The easiest way to solve this is to designate the existing tr as a .template and clone it in your loop, make the necessary changes (filling in the values) and then appending it.
Fixing some other unclear things this gives the following
$.getJSON("http://1.handy-post-402.appspot.com/show?callback=?", function(records) {
for (var i = 0; i < records.length; i++) {
//Clone the row/unit which we will be using for each record (the class should refer to the type of item it /actually/ is)
row = $(".row.template").clone();
//The template class is hidden, so remove the class from the row/unit
row.removeClass("template");
var map = records[i].propertyMap;
var content = map.isi;
var user = map.No_HP;
var date = map.tanggal;
//Make the required changes (find looks for the element inside var row)
row.find('.date').text(date);
row.find('.nohp').text(user);
row.find('.content').text(content);
//Append it to the parent element which contains the rows/units
$("tbody").append(row);
}
});
See functional demo: http://jsfiddle.net/YYTkK/13/
You must append a new row in the table in every loop. Here's the working fiddle.
fiddle
$.getJSON("http://1.handy-post-402.appspot.com/show?callback=?", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.isi;
var user = map.No_HP;
var date = map.tanggal;
var row = '<tr><td>'+date+'</td><td>'+user+'</td><td>'+content+'</td></tr>';
$('#valuetable').append(row);
}
});
what you have to do is create dynamic "tr" s and append to tbody and use thead for header and separate the body using tbody and create tr s on each iteration and after the loop append that tr to tbody. that will do the job, as you do now it will override the values at each iteration.
#chamweer answer is correct you have to create a new tr with td's dynamically
like this:
http://jsfiddle.net/YYTkK/14/
Because you're overriding the same td's over and over again.
$.getJSON("http://1.handy-post-402.appspot.com/show?callback=?", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.isi;
var user = map.No_HP;
var date = map.tanggal;
// create a temporary tr
var tr = $("<tr />");
// append to the tr the td's with their values
tr.append($("<td />").text(date), $("<td />").text(user),
$('<td />').text(content));
// finally append the new tr to the table's tbody
$("#js-tbody").append(tr);
}
});

Get id from html table when clicking an input inside the table

How can you get the id of a table when you click an input element?
I don't need the rowId etc.
I've tried parentNode.id but I can't seem to get the id.
In the end I'd like to do something like this:
var tabelid = INPUT....parentNode.parentNode.id;
var table = document.getElementById(tabelid);
Example:
How about this:-
Demo
Html
<table id="tblTest">
<tr>
<td>
<input type="text" id="txtTest" onclick="getParent.call(this)" />
</td>
</tr>
</table>
I am using call here so that i get the elements context inside the getParent event callback.
Javascript
function getParent()
{
var parent = this.parentNode;
var tagName = "table";
while (parent) { //Loop through until you find the desired parent tag name
if (parent.tagName && parent .tagName.toLowerCase() == tagName) {
alert(parent .id);
return;
}
else
{
parent = parent .parentNode;
}
}
}
If you are using Jquery:-
in the click event you can just do $(this).closest('table').attr('id')
If you are using jQuery you can use closest to find the closest matching ancestor like so:
var tableID = "";
$(document).ready(function(){
$('input[type="text"]').click(function(e){
tableID = $(this).closest('table').attr('id');
});
]);
Edit:
If you actually want to do something with that table (for instance add a class), you could do the following:
$(document).ready(function(){
$('input[type="text"]').click(function(e){
tableID = $(this).closest('table').addClass('myClass');
});
]);
This simply removes the need to fetch the table ID, store it, and then fetch the table based on it's ID. Since you already found the table in order to get its ID you can just manipulate it right away.
You have to ascend the DOM from TD to TABLE keeping in mind that browsers may inject a TBODY if you haven't specified it. So, your code should look something like this:
var tableCells = document.getElementsByTagName('td'),
cellCount = tableCells.length,
i;
for (i = 0; i < cellCount; i += 1) {
tableCells[i].onclick = function () {
var tableId = getTableId(this);
console.log(tableId);
};
}
function getTableId(node) {
var element = node;
while (element.tagName.toLowerCase() !== 'table') {
element = element.parentNode;
}
return element.id;
}
Check out the demo.

Getting third cell of each row

var Rows = $("#tableid tbody tr");
Rows.each(function(index, element) {
var thirdCell = $(this+":nth-child(3)").text();
alert(thirdCell);
});
Something in the var thirdCell line is not working correctly. Each row has four children, all td tags. I want to get the text inside the third cell.
Try something like below,
var Rows = $("#tableid tbody tr");
Rows.each(function(index, element) {
var thirdCell = $(this).find('td').eq(2).text();
alert(thirdCell);
});
this is not a string, it's a jquery object, so it can't be appended to when you are building your new selector. You could do it like this:
var selector = $(this).selector;
var thirdCell = $(selector+":nth-child(3)").text();
alert(thirdCell);
http://jsfiddle.net/2URV7/
This will not work because tr has no text. it has TDs. you can apply though html() to get the innerHTML of the tr, or use text() on tds if they actually contain text.
you can get all cells from each row by 0 based index
Rows.each(function(index, element) {
var thirdCell = $(this.cells[2]).text();
alert(thirdCell);
});
or you can get it in original selector
var Third = $("#tableid tbody tr > td:nth-child(3)");
Third.each(function(index, element) {
var thirdCell = $(this).text();
alert(thirdCell);
});

JavaScript DOM : add an attribute to a <tr>

I want to create a JavaScript function that parses my HTML page, get the Table by it's ID, and after that, add a class attribute to each <tr> as if the line is the 1st, I'll add :
class="line1" to the <tr>
but if the line is the second, I'll add class="line2" to the <tr>
How to do please
If I understand you corrrectly, you want to alternate the class names to get some kind of zebra style right?
var table = document.getElementById('yourTableId');
var rows = table.rows;
for(var i = 0, l = rows.length;i < l; i++) {
rows[i].className = 'class' + ((i%2) + 1);
}
See the HTML DOM Table Object.
its very easy in jquery ... as below :-
$(document).ready(function() {
//for table row
$("tr:even").addClass("AlternateBG1");
$("tr:odd").addClass("AlternateBG2");
})
BUT IN JQUERY...
var table = document.getElementById("yourTableId");
for(var i in table.rows){
table.rows[i].className = 'line'+(i+1).toString();
}
It is easy without jQuery:
oTBody=document.getElementById("tBodyId");
//for (key in oTbody.childNodes) {
for (var nPos=0, nLength = oTbody.childNodes.length; nPos<nLegth; nPos++)}
oRow = oTbody.childNodes[nPos];
if (oRow && oRow.tagName && oRow.tagName.toLowerCase() == "tr") {
oRow.className = (bNormalRow? sClass1:sClass2);
bNormalRow = !bNormalRow;
}
}
With jQuery is really simple, do something like:
var i = 1;
$("#myTable tr").each(function() {
$(this).addClass("line"+i);
i++;
});
Where #myTable is your table id, and $(this) inside each function will be the current element on the cycle.

Categories