Javascript: Set ID to a child existing table - javascript

I need to assign/set a unique ID to child tables per Javascript. The main parent table has an ID but the child tables and further child tables within child tables don't.
How can I set an ID to the 1st child and second child tables "on page load"?
<table id="main parent table">
<tbody>
<tr>
<td>
<table>
<tbody>
<tr>
<td>
<table>
<tr>
<td></td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>

You are probably looking to do something like this (fiddle here) :
$('table').each(function(eq, el) {
el = $(el);
if(typeof(el.attr('id')) === "undefined") {
el.attr('id', 'table-' + eq);
}
});
You check every table on site and if it has no id, you assign id of "table-" to each one in the tree.

Use Jquery loop on Top table children loop on inner table. find and addClass on them.

Related

How to get the <tr> of a clicked element in a table

I have a table with several <tr>s and each one has several <td>s. The content of these columns can be another html element (for example a textbox) or just text.
My question: how I can get the rest of the siblings of one clicked element inside this column? I mean, how I can know to which <tr> this element belongs, to <tr> #3 or <tr> #5?I don't have a index per <tr> to control
Example:
If I click the textbox of column #1 in row #5, I want that the content of column #2 in row #5 change. I don't know how to do it because my <tr> doesn't have an index.
Using jQuery, add this to the event handler. This will provide you with a collection of table cells:
var columns = $(this).closest('tr').children();
// .eq() is 0-based, so this would retrieve the fourth column
columns.eq(3);
You can find the index of a row using the index() function.
$('input').click(function(){
var index = $(this).parents('tr').index();
alert('you click an input on row #' + index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td></td>
</tr>
</table>
Use closest to get the parent TR element.
$('your_element').click(function(){
var tr = $(this).closest('tr');
var element1 = $(tr).find('element_to_find');
});
You can also use the :eq operator to find the td.
$('your_element').click(function() {
var tr = $(this).closest('tr');
var col3 = $("td:eq(2)", tr);
}

Add row to table inside a loop error

I had a table inside a loop, and I want to add a row to the table by clicking a button "add row". Here is my code
HTML:
<div id="popUp" style="display: none">
<input type="button" value="Cancel" onclick="closePopup()">
<input type="button" value="ADD" onclick="addRow(this)"/>
</div>
#for (int i = 0; i < 3; i++) {
<table id="table #i" class="tableSum">
<thead>
<tr>
<td>Items</td>
<td>Quantity</td>
<td>Price</td>
</tr>
</thead>
<tbody>
<tr>
<td>Apple</td>
<td>5</td>
<td>100</td>
</tr>
<tr>
<td>Organe</td>
<td>5</td>
<td>200</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td></td>
<td></td>
</tr>
<tr><td colspan="3"><input type="button" class="addRow" onclick="addRow(this)" value="ADD ROW"/></td></tr>
</tfoot>
</table>
}
then in javascript i wrote function:
function addRow(table) {
$(table).find('tbody tr:last').clone().appendTo(table);
}
but it does not add a row. If I use the function without parameter "table", the new row will be added to all tables inside a loop.
My desired outcome is: When the user clicks the button a new row will be added only in the one table, not to all.
onclick="addRow(this)" on a td. this will represent the surrent td. Not the table. You may pass the id or some selector of the table or find the parent table in with your script.
You can use parents() to find the parent table.
function addRow(td) {
var table = $(td).parents('table');
var cloned = table.find('tbody tr:last').clone();
table.find('tbody').append(cloned);
}
And also if you want all the events to work then use clone(true). Else you have to bind the events to the tr.
You need to use closest to find its parent table first:
function addRow(table) {
$(table).closest('table')//find parent table
.find('tbody tr:last')//find last tr of the table
.clone()//clone it
.appendTo($(table).closest('table').find('tbody'));//append it to tbody
//append to 'tbody' not this row
}
As per your updated question, here you go:
function addRow(table) {
$(table).parent()//find parent div
.next()//get the table
.find('tbody tr:last')//find last tr of the table
.clone()//clone it
.appendTo($(table).parent().next().find('tbody'));//append it to tbody
//append to 'tbody' not this row
}

checking number of td tags in a dynamic table and divide them into two equal tr tags

The question title might seems ambiguous but I will try to explain in detail over here.
So I am generating a dynamic table based on the JSON data. Inside the table I have few tags and in one of the tag I am further populating table data enclosed in tags. Number of tables inside the td tag might varies but the maximum number of tables are 4. Here is the rough HTML markup which is generated after the table is populated.
Current mark up
<table>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
Expected mark up
<table>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
</tr>
<tr>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
As you can see in the third tag I have 4 tag which contains individual tables. What I am trying to achieve if the number of tags in the third row is greater than 2 then I should create another tag below that and divide the 4 tags (which contains tables) into 2 tags (with 2 tags each).
Since the tables are generated dynamically I don't have a predefined HTML mark up.
This is my relevant JS function
drawRunningDailyDoublesTables: function (events, table) {
var indexes = $(table).data('BetTableData').eventIndexes;
table.innerHTML = '';
// Drawing STAB / NSW product selection
betTable.drawBetTypeProductSelection(table);
// Error space
betTable.drawErrorSpace(table);
var trForTables = $('<tr/>')
.appendTo(table);
// Drawing tables for doubles
$.each(indexes, function(j, index) {
var betTableData = new BetTableData();
betTableData.setMarketId(events[index].markets[0].id);
var doubleTable = $('<table/>')
.data('BetTableData', betTableData);
// Names and info of races
betTable.drawHeaderForDoubles(doubleTable, events[index], 3);
// Horse selections
betTable.drawSelectionsForRunningDoubles(table, doubleTable, events[index], j+1);
// here I am generating the td tag with tables as mentioned in the question. It could be 2,3 or 4 depending on the different situation.
$('<td style="vertical-align: top;"/>')
.appendTo(trForTables)
.append(doubleTable)
// Footer
createFooterRowForRunningDoubles("white", 2, table, doubleTable, j+1);
});
// draw button for betting
betTable.drawExoticBetBtnForDoubles(table);
betTable.selectDefaultRadioProduct(table);
},
Please see this fiddle:
http://jsfiddle.net/MXGBu/2/
var thirdRow = $('table:first>tbody>tr:nth-child(3)');
var tablesInThird = thirdRow.find('table');
if(tablesInThird.length === 4)
{
thirdRow.after('<tr class="arse"></tr>');//creates a new tr after 3rd row
tablesInThird.eq(2).parent().appendTo($('tr.arse')); //adds 3rd table
tablesInThird = thirdRow.find('table');
tablesInThird.eq(2).parent().appendTo($('tr.arse')); //adds 4th table
}

Combining Rows in Javascript

I'm looking for some help on the Javascript angle of this problem. I have a table that goes like...
<table>
<tbody>
<tr> (Row 1)
<td colspan="3">
<p>This Says Something</p>
</td>
</tr>
<tr> (Row 1a)
<td>
<select option>
</td>
</tr>
<tr> (Row 2)
<td colspan="3">
<p>This Says Something</p>
</td>
</tr>
<tr> (Row 2a)
<td>
<select option>
</td>
</tr>
<tr>
<td colspan="3">
<p>This Says Something</p>
</td>
</tr>
<tr>
<td>
<select option>
</td>
</tr>
<tbody>
</table>
There are actually more like 20 rows and row a's but I didn't think I'd want to copy them all.
I basically need to add a container row (a single row) around every two rows (# and #a). Something like:
<tr> (Container Row 1)
<td>
+<tr> (Row 1)
+<tr> (Row 1a)
</td>
</tr>
It needs to cycle through the whole table. Somehow it has to retain the HTML data inside since all of the "a"s have options.
I hope this makes sense...
Any help would be greatly appreciated, as I'm at a loss. I'm novice at best at javascript and am struggling my way through the DOM and TOM methods.
Thank you so much in advance for any help or headway.
[EDIT] For clarification, the table is already constructed from a third party database, I am editing it after it's constructed. I guess this clarifies why it would have to be javascript to be done through the DOM.
Embed another table:
<tr> (Container Row 1)
<td>
<table>
<tr><td>(Row 1a)</td></tr>
<tr><td>(Row 1b)</td></tr>
</table>
</td>
</tr>
Or if you are wanting to do that via Javascript, you can give the parent <td> an id and set it's innerHTML.
<tr> (Container Row 1)
<td id='rowX'>
</td>
</tr>
document.getElementById('rowX').innertHTML = "<table><tr><td>(Row 1a)</td></tr><tr><td>(Row 1b)</td></tr></table>";
As mentioned in another answer you can't add tr elements directly in td like you are trying.
You would first create an inner table.
If you were using jQuery you would do something like this:
//setup some click actions just to prove that they remain attached even after moving
$('#outterTable tr').click(function(){
alert('You clicked on row: '+$(this).text());
});
//update the table (group each even row with the one after it)
$('#outterTable tr:even').each(function() {
var $tr1 = $(this),
$tr2 = $tr1.next('tr'),
$t = $('<table></table>');
$('<tr></tr>').append($t).insertBefore($tr1);
//click actions will remain attached
//if that is not required, than use $tr1.remove()
$t.append($tr1).append($tr2);
});​
See this live jsFiddle example.
without jQuery it may look like that:
<script type="text/javascript">
<!--
function fx(table)
{
var tmp=document.createElement('table');
tmp.appendChild(document.createElement('tbody'))
while(table.rows.length)
{
if(table.rows.length%2==0)
{
var wrapper=tmp.lastChild.appendChild(document.createElement('tr'));
wrapper.appendChild(document.createElement('td'));
wrapper.getElementsByTagName('TD')[0].appendChild(document.createElement('table'));
wrapper.getElementsByTagName('TD')[0].lastChild.appendChild(document.createElement('tbody'));
}
wrapper.getElementsByTagName('TD')[0].lastChild.lastChild.appendChild(table.getElementsByTagName('TR')[0])
}
table.parentNode.replaceChild(tmp,table);
tmp.setAttribute('border',1);
}
window.onload=function(){fx(document.getElementsByTagName('table')[0]);}
//-->
</script>
Example#jsFiddle
But: why do you need this grouping?
If the only benefit is a visible grouping I would prefer to do this by setting the borders of the cells .
Give all cells a border and to the even a border-top:none / to the odd a border-bottom: none

Selector and Iterating Through a Table Within a Div

I have been working on this and cannot get this iterator to work. I have the following HTML and am trying to iterate through all rows (except the first row) and extract the values in cells (td) 2 and 3 :
<div id="statsId">
<table width="220" cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="65"/>
<td width="90"/>
<td width="65"/>
</tr>
<tr style="font-weight: bold;">
<td align="left">$1.00</td>
<td>
UserID1
</td>
<td>Single</td>
</tr>
<tr>
<td align="left">$6.99</td>
<td>
UserID2
</td>
<td>Multiple</td>
</tr>
<tr>...
.....(snip)
I tried the following iterator to iterate through all except the first row of the table that is a child of "div#statsID" and get the values of the 2nd and 3rd cells (in the example, the first extracted cells would have values of "UserID1" and "Single"), but it doesn't work.
$('div#statsId > table tr:not(:nth-child(1))').each(function(i, ele) {
var secondCol = $('td:nth-child(2)', ele).innerHTML
var thirdCol= $('td:nth-child(3)', ele).text()
.....
});
Any suggestions on how to specify and iterate through the rows (except the first) of a table that is a child of a div would be appreciated.
$("#statsId > table tbody tr:not(:first)").each ( function() {
var secondCol = $(this).find('td:nth-child(2)').html();
var thirdCol= $(this).find('td:nth-child(3)').text();
});
Note
You can use the id selector independently. No need to use the tag name.
There is no innerHTML for a jQuery object. Use html() instead

Categories

Resources