Saving state of expanded child rows in datatable after reload div - javascript

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

Related

How to get checked rows' values from html table on a sidebar using GAS?

I have a table whose rows consist of 3 columns. 1º is a checkbox, 2º contains the colors and the 3º contains the hex.
As the user selects the colors desired by ticking the checkboxes, i imagine the colors being pushed into an arrat, that will be written to a cell as the user clicks on the save button.
I've borrowed this snippet from Mark, but it doesn't seem to run in my context:
var checkboxes = document.getElementsByTagName("input");
var selectedRows = [];
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var secondColumn = currentRow.getElementsByTagName("td")[1];
selectedRows.push(secondColumn);
};
console.log(selectedRows)
}
This is the javascript part running to load and populate the table and I'm not sure where the above snippet woud go into:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
/**
* Run initializations on sidebar load.
*/
$(function() {
// Assign handler functions to sidebar elements here, if needed.
// Call the server here to retrieve any information needed to build
// the dialog, if necessary.
google.script.run
.withSuccessHandler(function (record) { //<-- with this
showRecord(record);
})
.withFailureHandler(
function(msg, element) {
showStatus(msg, $('#button-bar'));
element.disabled = false;
})
.getRecord();
});
/**
* Callback function to display a "record", or row of the spreadsheet.
*
* #param {object[]} Array of field headings & cell values
*/
function showRecord(record) {
if (record.length) {
for (var i = 0; i < record.length-1; i++) {
// Adds a header to the table
if(i==0){
$('#sidebar-record-block').append($($.parseHTML('<div class="div-table-row"><div class="div-table-header">Sel</div><div class="div-table-header">Color</div><div class="div-table-header">Hex</div></div>')));
}
// build field name on the fly, formatted field-1234
var str = '' + i;
var fieldId = 'field-' + ('0000' + str).substring(str.length)
// If this field # doesn't already exist on the page, create it
if (!$('#'+fieldId).length) {
var newField = $($.parseHTML('<div id="'+fieldId+'"></div>'));
$('#sidebar-record-block').append(newField);
}
// Replace content of the field div with new record
$('#'+fieldId).replaceWith('<div id="'+fieldId+'" class="div-table-row"></div>');
$('#'+fieldId).append('<input type="checkbox" class="div-table-td" id=CB"'+fieldId+'"name="checkBox" </input>')
.append($('<div class="div-table-td">' + record[i].heading + '</div>'))
.append('<div class="div-table-td">' + record[i].cellval + '</div>')
}
}
}
</script>
Sample of how to get the checked tickboxes an button click
Assuming all your checkboxes are tied to a row, you can loop through all checkboxes with a query selector,
access their checked status
and save the indices of those checkboxes.
Those indices will be the same as when looping through the corresponding table rows.
Sample implementing a button click event:
var saveButton = document.getElementById("myButtonId");
saveButton.onclick = function(){
var checkedRowIndices = [];
$('input[type=checkbox]').each(function( index ) {
if($(this)[0].checked{
checkedRowIndices.push(index);
}
});
};
//now get the rows with those indeices and do something with them

javascript highlight multiple rows

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

Kendo mvc refreshing cell value

I'm trying to refresh grid cell using javascript. I'm refering to two cells which I want to refresh, but command refresh() or read() doesn't working:
Refresh()
Read()
There are multiple way you can update cell value in grid .
1.In data bound event
function Grid_DataBound(e) {
var rows = e.sender.tbody.children();
for (var j = 0; j < rows.length; j++) {
var row = $(rows[j]);
row[0].cells[i].innerHTML = 'Your UpdatedText ';
}
}
2.In inline control event (client template) i.e. your column needs to be define as a ClientTemplate having any control and call a function on any of the event.
function ControlChange(args) {
var currentRow = $(args.currentTarget).closest("tr")[0];
//If needed you can access datasource
var dataItem = $("#Report_Grid").data("kendoGrid").dataItem(currentRow);
currentRow.cells[4].innerHTML = 'Your UpdatedText ';
}

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

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