Jquery: hide all table columns only if all its value is "NA" - javascript

For eg.
col1 col2 col3 col4 col5 col6
1 pass NA Pass NA NA
2 pass NA pass NA pass
3 fail NA pass NA NA
Then hide col3 and col5. Resulting table is below:
col1 col2 col4
1 pass Pass
2 pass pass
3 fail pass
col3 and col5 is hidden now.
Note : I am populating all rows through ajax. For each rows ajax is triggered.
Here is my existing code:
function hideOneValueColumns(table_id, ignore_row_class, ignore_column_class) {
var row_count = $('#' + table_id + ' tr:not(.' + ignore_row_class + ')').length;
if (row_count > 2) {
//first go through the column headers
$('#' + table_id + ' th').each(function (i) {
//only process the column if it isn't one of the column we should ignore
if (!$(this).hasClass(ignore_column_class)) {
//get all cells of the columns (in order to show or hide them)
var all_cells = $(this).parents('table').find('tr td:nth-child(' + (i + 1) + ')');
//get the cells we'll use to decide whether we want to filter the column or not
var filtered_cells = $(this).parents('table').find('tr:not(.' + ignore_row_class + ') td:nth-child(' + (i + 1) + ')');
//array containing the list of different values in a column
var values = new Array();
//gather the different cell values
filtered_cells.each(function () {
var value = this.innerHTML;
// gather all cells which has values NA
if (values == 'NA') {
values.push(value);
}
});
//hide if less than 2 different values and show if at least 2 different values
if (values.length == $('#' + table_id + ' tr').length) {
$(this).hide();
all_cells.hide();
} else {
$(this).show();
all_cells.show();
}
}
});
} else {
$('#' + table_id + ' th').show();
$('#' + table_id + ' tr td').show();
}
}
// call the method
// spcl is table id
hideOneValueColumns('spcl', 'filters', 'no-hide');

You need to loop over each table row and, for each column, work out if the cell contains 'NA'. If it does not, then leave the entire column alone.
In this code snippet I get the number of columns from the first row (assuming them to be row headers). Then, for each number of columns, for each row, get that column. The default functionality I have done here is to hide the column. If any of the cells in the column does not contain NA, then show the column.
"use strict";
function hideOneValueColumns(table_id) {
var columnCount = jQuery('#'+table_id+' tr:first-of-type th').length + 1;
for(var i = 1; i < columnCount; i++) {
var func = 'hide';
jQuery('tr:not(:first-of-type)').each(function(){
var $td = jQuery(this).find('td:nth-child('+i+')');
if($td.text() != 'NA') {
func = 'show';
}
});
jQuery('tr td:nth-child('+i+'), tr th:nth-child('+i+')')[func]();
}
}
hideOneValueColumns('some_id');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="some_id">
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col6</th>
</tr>
<tr><td>1</td><td>pass</td><td>NA</td><td>Pass</td><td>NA</td><td>NA</td></tr>
<tr><td>2</td><td>pass</td><td>NA</td><td>pass</td><td>NA</td><td>Pass</td></tr>
<tr><td>3</td><td>fail</td><td>NA</td><td>pass</td><td>NA</td><td>NA</td></tr>
</table>

Related

Distribute table columns equally over the page

I have a content placed in a table:
<table class="table table-hover" id="anliegenGrammatik"></table>
and this is my jQuery where I have AJAX request and using the response I populate (append) the table above.
success: function(response) {
$.each(response, function(index) {
$.each(response[index].synonyms, function(index2) {
$('#anliegenGrammatik').append('<tr> <td>' + response[index].synonyms[index2] + '</td> </tr>');
});
});
},
But it has a lot of data and like this it produces several hundred rows. How can I make in jQuery that it distributes columns and rows equally over the page. For example, instead of having one <tr> with 100 <td>s, I would like to have 4 <tr> and 25 <td>s in each row.
Is this even possible?
success: function(response) {
$.each(response, function(index) {
var item = 1;
var totalItems = response[index].synonyms.length;
var numRows = 4; // number of rows
var cellsRow = Math.floor(totalItems/numRows); // number of cells per row
var cells = '';
$.each(response[index].synonyms, function(index2) {
cells += '<td>' + response[index].synonyms[index2] + '</td>';
if((item % cellsRow == 0) || item == totalItems)
{
$('#anliegenGrammatik').append('<tr>'+cells+'</tr>');
cells = '';
}
item ++;
});
});
},

jquery set innerHTML for a cell in table

I want to print a value in each table cell after creating it dynamically.
<table id="MapDetails"><tr>
<td/><td/><td/><td/>
var colIndex = 4;
foreach(MapDetail geMapDetail in Model.mapDetails)
{
<td class="test">
<script>{getPosition(#geResult.assessmentId, #colIndex, #rowIndex, '#geResult.ResultValue');}</script>
</td>
colIndex++;
}
</tr></table>
My script
THIS DOES NOT WORK
function getPosition(id, colIndex, rowIndex, resultValue) {
var element = '#' + id;
var cell = $('#MapDetails tr:eq(' + rowIndex + ') td:eq(' + colIndex + ')');
if($(element).index() == colIndex){
cell.innerHTML = resultValue;
}
}
THIS WORKS ONLY FOR THE FIRST CELL
function getPosition(id, colIndex, rowIndex, resultValue) {
var element = '#' + id;
var cell = $(".test").closest('tr').find('td').get(colIndex);
if($(element).index() == colIndex){
cell.innerHTML = resultValue;
}
}
It is mostly a algorithm problem. You must loop through all TRs and nested TDs and write that one value that you want to write.
$('#tableid').find('tr').each(function(index, element){
$(element).find('td').each(function(indexd, elementd){
$(elementd).html('blah blah');
});
});
I found my answer here: How to set table cell value using jquery
so i did:
var cell = $("#MapDetails").children().children()[rowIndex].children[colIndex];
and that's it! Cheers

Select All checkbox only selects checkboxes that are currently in the page [not in other page indices]

I have a jquery dynatable. Here is the screenshot of my current table
My problem is that when I clicked the select all checkbox, the only checkboxes that are in the first page of the table are selected (in each row) but the others remain unselected. Here is my code so far:
// I have omitted the table head part for the sake of simplicity
/********************************
TABLE BODY
********************************/
var tableRows = "";
//iterate each result object
for (var row in result.results.bindings) {
tableRows += "<tr>";
//iterate each value
for (var key in result.results.bindings[row]) {
if (result.results.bindings[row].hasOwnProperty(key) && (resultSetVariables.length==0 || _.contains(resultSetVariables, "?" + key))) {
var value = "x";
if( result.results.bindings[row][key].value != undefined ) {
val = result.results.bindings[row][key].value;
if(val.match(regexURL)) {
value = '' + val.substr(val.lastIndexOf('/') + 1) + '';
}
else
value = val;
}
tableRows += "<td>" + value + "</td>";
}
}
tableRows+='<td><input type="checkbox" class="singleSelect"> </td>';
tableRows += "</tr>";
// console.log(tableRows);
};
$("#results_container").children().detach();
//create unique id
var id = Math.floor( Math.random()*99999 );
//append a new table to the DOM
$("#results_container").append('<table id="result_table' + id + '" cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered"><thead><tr></tr></thead><tbody></tbody></table>');
$("#results_container").append('<input type="button" class="btn" id="calculate_similarity" value="calculate_similarity" style="float:right;"/>');
$("#results_container").append("<label style='float:right;'><input class='mahoutSelection' id='selectAll' type='checkbox' value='selectAll' style='float:right;'>selectAll</label>");
//append head and body to tabley
$('#results_container table thead tr').append(tableHead);
$('#results_container table tbody').append(tableRows);
$('#results_container table tbody').append(tableRows);
//add the results table
this.resultTable = $('#results_container table').dataTable({
"sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>"
, "sPaginationType": "bootstrap"
, "oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
});
$('input[id="selectAll"]').on('click', function(){
if ( $(this).is(':checked') ) {
$("input[class=singleSelect]").each(function () {
$(this).prop("checked", true);
});
}
else {
$("input[class=singleSelect]").each(function () {
$(this).prop("checked", false);
});
}
});
So how could I fix it so that, when I click the select all, it checks all checkboxes ?

Create Rows in a Table using Javascript - adds too many cells...>

I'm trying to create a table on the fly... it almost works but I have an issue with the number of cell it adds.
My table has 8 columns (monday to Friday plus a total column at the end).
Here is the fiddle for it: http://jsfiddle.net/kaf9qmh0/
As you can see, on row 1, it adds the 8 columns 3 times, then on row 2 it adds the columns twice and only on the last row does it only add 8 columns.
I suspect it is because Im using .append to add the rows as follows (line 105 in the fiddle) but my Javascript being very limited, Im not entirely sure how to make it stop add the columns to row 1 and 2.
$("#timesheetTable > tbody").append('<tr id="' + sourceTableRowID + '" data-tt-id="' + sourceTableRowID + '" class="timesheetRow row' + rowIndex2 + '"></tr>');
How can I make it to only add the cells (td) to the next row when it loops through rowIndex2 and increments it?
Can somebody point me in the right direction please?
You had a loop within a loop - which was causing the additional cells. Here's an updated fiddle; and here's an extract of the modified code:
function createSampleRows() {
var sourceTable = document.getElementById('activityTable');
var sourceTableRows = sourceTable.rows.length;
var targetTable = document.getElementById('timesheetTable');
var rowindex;
var targetTableColCount;
for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) {
if (rowIndex == 1) {
targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
continue; //do not execute further code for header row.
}
}
for (rowIndex = 0; rowIndex < (parseInt(sourceTableRows)-2); rowIndex++) {
var sourceTableRowID = document.getElementsByClassName('activityTaskRow')[rowIndex].id;
$("#timesheetTable > tbody").append('<tr id="' + sourceTableRowID + '" data-tt-id="' + sourceTableRowID + '" class="timesheetRow row' + rowIndex + '"></tr>');
};
// This loop was nested within the above loop
for (x = 0; x < targetTableColCount; x++) {
$("#timesheetTable > tbody > tr").append('<td id="' + x + '" style="width: 60px;height: 34px;" class=""></td>');
};
};

Creating html table using Javascript not working

Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE

Categories

Resources