For chrome, firefox, and safari the following code seems to work and be able to retrieve the id of the last tr in a table.
var table = document.getElementById( tableId );
var rowid = table.lastChild.lastChild.id;
The goal is to use each rows id to keep track of what row number it is. I am using javascript to dynamcially add and remove rows. The problem is that I need a unique identifier for each row so that rows can be removed. If say there are 4 rows and row 2 is removed, the count will be 1, 3, 4. If another row is added, it can't be 4 or there will be duplicate 4's. The correct way would be to renumber everything, (but there are many elements in each row tied to their count, thus making it near hard to re-number)
Is there a better way to be doing this? Or is there a simple fix for IE javascript?
try this:
var table = document.getElementById( tableId );
var trArr = table.getElementsByTagName('tr');
var tdArr = trArr[trArr.length - 1].getElementsByTagName('td');
var rowid = tdArr[tdArr.length - 1].id;
Related
I’m working on what I thought would be a simple project but is something I’m struggling with. I’m wondering if someone could review what I’m trying to do and give me some pointers on how to proceed.
The concept here is fairly simple...I thought - identify each table in an html file based on the "table" element, count the number of rows in each table and if the table has more than 10 rows, dynamically create a unique id for the table.
I know how to do all this (for the most part) but it doesn’t respond how I anticipate.
Here’s my initial javascript code attempt to dynamically create and insert the unique table id’s:
/* This function dynamically sets a unique id to each table found in the html page: */
function set_table_id(){
var num_tables = document.getElementsByTagName("table"); //determine the number of “table” nodes in the html
//alert("set_table_id function: The total number of table elements are: " + num_tables.length);
if (num_tables) { //if one or more table nodes are found…
var id_name = "dataTbl_"; // create the prepend string for table id value
var n = 1;
var i;
//for each table node found…
for (i=0; i < num_tables.length; i++) {
var id_name_new = id_name + n; //create the next unique table id from the prepend string
n++;
num_tables[i].id = id_name_new; //apply the latest table id to the current table
//this will be the call to the function to apply the datatables javascript to each table that has more than 10 rows:
//num_tables[i].dataTable();
}
}
}
When I run the above js code there are no errors when I review the Inspect Element Console, but the unique id’s never get inserted into the table elements.
This should run through the html code, identify each table and dynamically apply (insert) a unique id to each table but it's not.
Any help is greatly appreciated.
This jQuery selector will find all tables that have 10 or more <tr> children and apply the ID and DataTables to each.
$(document).ready(function() {
$("table > tbody > tr:nth-child(10)").closest("table").each(function(index) {
var tableId = "dataTbl_" + (index + 1); //index is zero-based, so add 1
$(this).attr("id", tableId); //set the ID attribute
$(this).dataTable();
}
);
});
Heres is a JSFiddle, based on the on in your comment, which demonstrates it:
https://jsfiddle.net/5cgbdLzt/2/
Within that fiddle, I added a button that will alert the IDs to you, where you can see clearly that the ID of the table with fewer than 10 rows has an ID that is undefined.
Note: DataTables uses jQuery as a dependency, so it's assumed you can use jQuery selectors rather than strictly vanilla JS.
I'm trying to make a barcode scanner and I have a problem when some product doesn't exist it creates a new array with JavaScript and sends the problem to the that table. My problem is that I can't edit the table with innerHTML
JavaScript Function:
var table = document.getElementById("listViewTable");
var tableF = document.getElementById("listTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var td1 = document.createElement("td");
//row.innerHTML = '(A few <td> and an <input>)';
td1.innerHTML = '(More <td> and another <input>)';
row.appendChild(td1);
row.className = "tableCell newSKU";
That commented line row.innerhtml is what I tried to achieve but I.E does not support it.
This should be the end result:
The last product in yellow can't be put in the same table and as such does not have the same style as the others.
From ppk's guide to browser quirks:
In IE9 and lower innerHTML refuses to work on tables and selects. Solve this by using pure DOM methods instead. See this explanation of the table behaviour by innerHTML’s inventor. I assume something similar goes for selects.
Use createElement, appendChild and friends to create the cells.
i need to change the color of kendo grids row by using it's index no.
i tried using this but nothing happened.
var gview = $('#SearchResult').data().kendoGrid;//searchresult is grid's id
var dataRows = gview.items();
var rowIndex = dataRows.index(gview.select());
gview.tbody.find("tr:eq("+rowIndex+")").css("background-color", "green");
It's not throwing any error in debugger but not giving any result.
You need to find Uid of a row by its index and find tr by its data-uid, check below function
function ChangeGridRowByIndex(index) {
var grid = $("#SearchResult").data("kendoGrid");
var gridData = grid.dataSource.view();
var currentUid = gridData[index].uid;
var currenRow = grid.table.find("tr[data-uid='" + currentUid + "']");
$(currenRow).addClass("red");
}
Hope this will help you :)
Given that kendo does not give an option to control the background color of a single row directly (that I know of). But you must apply the new color after the table is rendered and you might also need to apply it after every refresh of the table also (kendo should have events thrown for this). Once kendo finshes painting it, grab the table element in your page, by default kendo gives it a class="k-grid-content". Using jquery it would look something like this
var differentRowElement = $('.k-grid-content').find('tr').eq(index).css('background-color', 'red');
Tested it on http://demos.telerik.com/kendo-ui/grid/index running this in the console
$('.k-grid-content').find('tr').eq(3).css('background-color', 'red');
Here's my latest version of this code. The 1st line iterates through the rows of a table skipping over the 1st row. For each row I test to see if the (class='dim') state of one of 8 tag elements (index j) on that row matches the corresponding !'dim' state of a set of 8 filters that the user can toggle. The idea is to set any rows where the 'active' filter / 'dim' tag states line up, to the 'hide' class, so they can disappear from the table that the user sees. The CSS for disappearing it is: .hide {display:none;}
It's that last 'if' statement that's killing me. I've tried dozens of versions but I always get some form of syntax error, undefined variable, etc. In that line of code here I've removed my latest set of +, ', " characters to better show clearly what I'm trying to do.
I don't just want something that works to replace this code. And I'm not interested in the shortest trickiest way to do it. I'd like to see some simple obvious code that I could easily understand a year from now so I can solve problems like this myself. Thanks in advance.
var thisRow = $('tbody tr:gt(0)').each(function() {
for (var i=0,j=4;i<8;i++,j++) {
if (!$('.butt').eq(i).hasClass('dim')) {
if (thisRow.nth-child(j)).hasClass('dim')) $(this).addClass('hide');
else $(this).removeClass('hide');
}
}
}
Above this line is the question as I first asked it. Below this is the complete function in case anyone else might find this useful. Thanks to Mr. Pavlikov for the lesson!
function filterTbl() { //Hide rows that don't satisfy all active filters
var butts=$('.butt'); //Each filter button has class 'butt'
$('tbody tr:gt(0)').each(function() { //iterate each table row except the 1st
var thisRow = $(this); //the row being examined
var chilluns = thisRow.children(); //all td's in the row being examined
for (var i=0,j=4;i<8;i++,j++) {
if (!butts.eq(i).hasClass('dim')) { //If this filter is active
//and If the corresponding tag is not active (is 'dimmed'), then hide this row
if (chilluns.eq(j).hasClass('dim')) thisRow.addClass('hide');
else thisRow.removeClass('hide'); //else unhide this row
}
}
});
}
First of all you should be getting thisRow variable like this (not like you are currently doing)
$('tbody tr:gt(0)').each(function() {
var thisRow = $(this);
}
And what does nth-child stand for? Use nth-child selector correctly or use siblings at least if you are willing to compare one row with other rows. I didn't quite understand what are you trying to do, but hope this helps.
And some usefull tips. You do not need to find $('.butt') EVERY TIME in the loop, just find it once before your each loop:
var butts = $('.butt');
So now you will be able to replace
$('.butt').eq(i)
with
butts.eq(i)
This is significant speedup.
Also if n-th child you are trying to find is something that is inside thisRow, find children and do .eq() on them.
In the JSFiddle, I am trying to generate divs dynamically using javascript. Those divs will contain tables where the last two rows can be incremented using the add button.
I have tried the code in the fiddle.
The ins_row() function is used to add rows in the table which are generated within the divs.
The addEvent() function is used to generate divs
When the Add product button is clicked a div containing a table with one row will get generated.
When the add button is clicked the last two rows should keep on getting added as per the clicks. If the remove button straight to the div is clicked the whole table and div should be deleted.
When the remove button straight to the generated rows is clicked, only that row should be deleted and not the whole div.
Problem
The problem here is the divs with table are getting generated but I couldn't figure out how to add the rows in the table.
See it in action here
Expected output
Note: I have just pasted the external JS file into the javascript column of the above fiddle as I don't have the resource link.
Present output
I hope I have presented the question understandable, if anything is not clear, Please let me know
I believe I have properly understood your requirement.
Try out this fiddle http://jsfiddle.net/Kucuk/14/
It uses jquery though - its just a sample sort of thing that you could probably base your own code off. Its all doable in plain old JavaScript, if that's what you prefer. The styling is a bit off, but that you can handle I hope.
Do let me know if this helps you in some manner.
Generally, I use jQuery's appendTo() function alongwith a dummy html structure. I store this in a variable & follow it up with further attribute manipulation.
To get an idea of what I am talking about, just check this fiddle: http://jsfiddle.net/GGS4N/
This is in answer to another question Smooth out this jQuery toggle animation?. Focus on the methodology as listed below:
To create a dummy HTML structure(generic in nature).
On your desired event, triggering of population and manipulation of the dynamic elements into the dom, with giving them an identifiers and manipulating other specific attributes, and as seen in the fiddle, even animating them.
If you prefer raw JS, as seen from your code, you can implement the same functionality in raw JS too! :)
Try this fiddle to see if it works for you.
In this example, when you click on add product, all 4 textboxes are created with an add more rows and remove div buttons.
When you click on add rows, last two textboxes are created with a remove row button.
Whenever the row count of a product is more than 1, the remove div button is hidden and is shown again when the row count is 1.
Is this more like what you expected?
http://jsfiddle.net/7AeDQ/81/
I achieved this by adding styles to widen the table and the cell containing the buttons. I also changed the buttons to input type="button".
Hope this works for you.
EDIT:
I have just noticed that I mixed up your expected output and present output. Working on expected output now.
Another pure js solution
<html>
<body>
<script>
var tblCount = 0
var tblIdStr = "productTbl";
function removeRow(id, rowNumber) {
var el = document.getElementById(id);
el.deleteRow(rowNumber);
}
function addTable() {
++tblCount;
tblId = tblIdStr + tblCount;
var args = "'" + tblId + "'";
var tblHtml = '<tr><td>Product name</td><td>Price</td><td>Competitor</td><td>Price</td></tr><tr><td><input type="text"></td><td><input type="text"><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="Add" onclick="addRow(' + args + ')"></td><td></td></tr>'
var tbl = document.createElement("table");
tbl.setAttribute("id", tblId);
document.getElementById("container").appendChild(tbl)
document.getElementById(tblId).innerHTML = tblHtml;
}
function addRow(id) {
var el = document.getElementById(id)
var rowCount = el.rows.length;
var row = el.insertRow(rowCount);
//console.log(row)
var args = "'" + id + "'" + "," + rowCount;
var tblRowHtml = '<td colspan=2></td><td><input type="text"></td><td><input type="text"></td><td><input type="button" value="remove" onclick="removeRow(' + args + ')"></td>';
//el.rows[rowCount].setAttribute("id", rowId);
el.rows[rowCount].innerHTML = tblRowHtml
}
</script>
<input type="button" value="Add new product table" onclick="addTable()">
<div id="container">
</div>
</body>
</html>