javascript highlight multiple rows - javascript

I have looked all over but can't find a good answer.
So what I'm wanting to do is highlight multiple rows on a table
Then if you click on a highlighted row it gets un-highlighted.
All of this works for me. The problem I'm having is when I un-highlight a row for some reason it won't highlight again.
function highlight_row() {
var table = document.getElementById("display-table");
var cells = table.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cell.onclick = function () {
var rowId = this.parentNode.rowIndex;
var rowSelected = table.getElementsByTagName('tr')[rowId];
rowSelected.className += "selected";
$(cell).toggleClass('selected');
}
}
}
I have changed out $(cell) with $(this) and that works but only re highlighting the cell I click on and not the whole row.
I'm at a lose here.
Thanks

If you want to highlight the whole row, you need to get parent tr
cell.onclick = function () {
$(this).parent('tr').toggleClass('selected');
}

Related

Saving state of expanded child rows in datatable after reload div

My application is working with database and when data in DB changes, my page is reloading. To show data I used bootstrap datatable. My datatable always has one child, hidden column and I want to save expanded state before refreshing page. I did it but I have 2 problems:
When I am expanding rows after reload, child rows has also expanded icon like parent-rows
expanded-row icon doesn't change
Here is a example what I want and what I get.
I was trying dynamically change tr class but it didn't work or just I was making it wrong.
My js code:
<script type="text/javascript">
function refreshtable() {
var openRows = [];
var table = $('#table').DataTable();
table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
var tr = rowIdx;
var row = table.row(tr);
if (row.child.isShown()) {
openRows.push(rowIdx);
}
})
$('#tablediv').hide();
$('#load').show();
$("#tablediv").load("mainrf.jsp");
setTimeout(function(){
var table = $('#table').DataTable();
var arrayLength = openRows.length;
var roww;
for (var i = 0; i < arrayLength; i++) {
roww = table.row(openRows[i]);
roww.child(format(roww.data())).show();
}
}, 500);
}
function format(value) {
var temprow = value.toString();
var pieces = temprow.split(/[\s,]+/);
var piece = pieces[pieces.length-1];
return '<table><tbody><tr><td>Comments: ' + piece + '</td></tr><tbody></table>';
}
</script>
I did it, by changing for loop. Now I am just triggering expand button click.
for (var i = 0; i < arrayLength; i++) {
$( 'td:first-child', table.row( openRows[i]).node() ).trigger( 'click' );
}

Replacing entire DIV with function

I'm attempting to start a div area with html in it and then replace that html with new html. I am currently trying to do so with the use of a function to simplify the creation of the html.
This is my function that creates a table based on input of rows and columns and a character.
function drawArt (x, y, char){
$( "#artArea").append("<table>");
indexY = 0;
while (indexY < y)
{
$( "#artArea").append("<tr>");
var indexX = 0;
while (indexX < x)
{
$( "#artArea").append("<td class=tableCell>" + char + "</td>");
indexX++;
}
$( "#artArea").append("</tr>");
indexY++;
}
$( "#artArea").append("</table>")
};
I'd like to be able to recall this function to redraw the table. So far this is what I have written but it seems to not work. Any tips?
$( "#genNew" ).click(function(){
var xGlobal = $("#numCols").val();
var yGlobal = $("#numRows").val();
var charGlobal = $("#drawChar").val();
$( "#artArea" ).replaceWith();
drawArt (xGlobal, yGlobal, charGlobal);
})
So, as suggested below changing "replaceWith" to "empty" fixed part of my problem. However, it broke another part of my program. I should be able to click on any character and get it to change to whatever was input, without changing the whole table, as so:
$( ".tableCell" ).click(function(){
charGlobal = $("#drawChar").val();
$(this).text(charGlobal)
})
Which part of my program is failing?
The big problem is you're creating invalid html. You always append to the #artArea table, so your markup will end up as
<table>
<tr></tr>
<td></td>
<td></td>
... etc
</table>
This is not what you want. What I suggest you could do is to simply create the appropriate html as a string inside drawArt and use `replaceWith to change the html
function drawArt (x, y, char){
var html = "<table>";
indexY = 0;
while (indexY < y)
{
html += "<tr>";
//-- snip, you get the idea!
}
html += "</table>"
return html;
}
and then
$( "#genNew" ).click(function(){
var xGlobal = $("#numCols").val();
var yGlobal = $("#numRows").val();
var charGlobal = $("#drawChar").val();
$( "#artArea" ).html(drawArt (xGlobal, yGlobal, charGlobal));
})
Working example: http://jsfiddle.net/0sh1wt01/1/
Having updated the question with a new requirement, I should address that too. The reason your click event handler does not work on the table cells is that click only affects elements which are on the page at the time the page loads. if you're dynamically adding new elements (as we are above) then you need to delegate the event to an element which does exist at page load. In this case we could use the artArea. Note you want .html not .text
$( "#artArea" ).on('click','.tableCell', function(){
charGlobal = $("#drawChar").val();
$(this).html(charGlobal);
});
Live example: http://jsfiddle.net/0sh1wt01/2/
You can replace the html with a new one.
This is the js code:
$("#start").click(function() {
var x = $("#rows").val(),
y = $("#columns").val(),
charx = $("#char").val();
//getting teh no of columns, rows and the character
$("#container").html("");
//empty the container first
var table = document.createElement("table");
for (var i = 0; i < x; i++) {
var tr = document.createElement("tr");
for (var j = 0; j < y; j++) {
var td = document.createElement("td");
td.innerHTML = charx;
tr.appendChild(td);
}
table.appendChild(tr);
}
//creating the table based on the values
$("#container").append(table);
//appending inside the container
});
Here is the Plnkr Link
Hope it works for you :)

OnClicks links to wrong button

I'm trying to link the button across every row to delete that row when clicked. However, every delete button is linked to the onclick delete of the last created row.
For example:
TABLE
Record 1 | deleteButton1
Record 2 | deleteButton2
Record 3 | deleteButton3
Actions:
clicks deleteButton1 ---> deletes the row with "Record 3"
clicks deleteButton1 ---> tries to delete the row with "Record 3" (a.k.a. nothing happens b/c row not found)
clicks deleteButton2 ---> tries to delete the row with "Record 3" (a.k.a. nothing happens b/c row not found)
HTML:
<table id="Table"></table>
JavaScript:
//Code snippet
for (var x = 0; x < itemArray.length; x++)
{
selectedItem = itemArray[x];
table = document.getElementById("Table");
row = table.insertRow(table.rows.length);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell1.innerHTML = selectedItem;
cell2.innerHTML = "<button>—</button>"; //Delete button across every row.
cell2.onclick = function () { removeRow(selectedItem); };
}
function removeRow(content, where)
{
var table;
table = document.getElementById("Table");
var iter;
for (var i = 0; i < table.rows.length; i++)
{
iter = table.rows[i].cells[0].innerHTML;
if (iter == content)
{
table.deleteRow(i);
}
}
}
Each onclick function references the variable selectedItem. After your for loop, that variable is set to the last item in the array. So, every button will reference that last item. Here is a demonstration.
I suggest using Javascript's parentNode and rowIndex to allow a button to reference its own parent row.
In my example below, rowIndex returns the index number of the tr that is the parentNode for the clicked cell (td). This index number can be used to remove a table row directly.
cell2.onclick = function () { removeRow(this.parentNode.rowIndex); };
function removeRow(x) {
document.getElementById("Table").deleteRow(x);
}
Working Example (jsFiddle)
You may need something like this :
http://www.codingforums.com/javascript-programming/170869-dynamically-add-delete-reorder-rows-table.html
Here :
for (var i= startingIndex; i< tbl.tBodies[0].rows.length; i++) {
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.one.data = count; // text
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_FS; // input text
tbl.tBodies[0].rows[i].myRow.two.id = INPUT_NAME_FS + count;
tbl.tBodies[0].rows[i].myRow.three.name = INPUT_NAME_FS_DESIGN; // input text
tbl.tBodies[0].rows[i].myRow.three.id = INPUT_NAME_FS_DESIGN + count;
// CONFIG: next line is affected by myRowObj settings
// CONFIG: requires class named classy0 and classy1
tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
count++;
}

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

Hide table column ondblclick

I have a table and I want to hide a column when I double click a column.
Code for hiding a column is practically all around Stack Overflow. All I need is a hint on how/where to add the ondblclick event so I can retrieve the identity of a <td> within a <table>.
Here are two solutions that should work. One done with jQuery and one with only standard Javascript.
http://jsfiddle.net/GNFN2/2/
// Iterate over each table, row and cell, and bind a click handler
// to each one, keeping track of which column each table cell was in.
var tables = document.getElementsByTagName('table');
for (var i = 0; i < tables.length; i++) {
var rows = tables[i].getElementsByTagName('tr');
for (var j = 0; j < rows.length; j++) {
var cells = rows[j].getElementsByTagName('td');
for (var k = 0; k < cells.length; k++) {
// Bind our handler, capturing the list of rows and colum.
cells[k].ondblclick = column_hide_handler(rows, k);
}
}
}
// Get a click handler function, keeping track of all rows and
// the column that this function should hide.
function column_hide_handler(rows, col) {
return function(e) {
// When the handler is triggered, hide the given column
// in each of the rows that were found previously.
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].getElementsByTagName('td');
if (cells[col]) {
cells[col].style.display = 'none';
}
}
}
}
With jQuery it is much cleaner. This method also uses event bubbling, so you don't need to bind an event handler to each table cell individually.
http://jsfiddle.net/YCKZv/4/
// Bind a general click handler to the table that will trigger
// for all table cells that are clicked on.
$('table').on('dblclick', 'td', function() {
// Find the row that was clicked.
var col = $(this).closest('tr').children('td').index(this);
if (col !== -1) {
// Go through each row of the table and hide the clicked column.
$(this).closest('table').find('tr').each(function() {
$(this).find('td').eq(col).hide();
});
}
});
You can do this way:
<td ondblclick="this.style.display = 'none';">Some Stuff</td>
Here this refers to current td clicked.
Working Example
To go unobtrusive, you can do that easily using jQuery if you want:
$('#tableID td').dblclick(function(){
$(this).hide();
});
Due to lack of answears I came up with a workaround, which is a big ugly, but it works fine.
On the window load event I decided to iterate the table and set each 's onclick event to call my show_hide_column function with the column parameter set from the iteration.
window.onload = function () {
var headers = document.getElementsByTagName('th');
for (index in headers) {
headers[index].onclick = function (e) {
show_hide_column(index, false)
}
}
}
show_hide_column is a function that can be easily googled and the code is here:
function show_hide_column(col_no, do_show) {
var stl;
if (do_show) stl = 'table-cell'
else stl = 'none';
var tbl = document.getElementById('table_id');
var rows = tbl.getElementsByTagName('tr');
var headers = tbl.getElementsByTagName('th');
headers[col_no].style.display=stl;
for (var row=1; row<rows.length; row++) {
var cels = rows[row].getElementsByTagName('td')
cels[col_no].style.display=stl;
}
}
Note: my html only had one table so the code also assumes this. If you have more table you should tinker with it a little. Also it assumes the table has table headers ();
Also I noted this to be an ugly approach as I was expecting to be able to extract the index of a table cell from the table without having to iterate it on load.

Categories

Resources