Distribute table columns equally over the page - javascript

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 ++;
});
});
},

Related

build unique table with JQuery AJAX

I have a script that builds a table and makes it editable once the user clicks on a cell. The User then leaves a comment and it will update the JSON file as well as the HTML table.
The problem I am having is that if I have two tables with separate JSON files, how can I implement the same script on both of the tables? Would I have to have two separate scripts for each table? How can I do it based off the ID of the table
JSON1:
[{"GLComment":"comment from table 1","EnComment":""},
{"GLComment":"","EnComment":""}]
JSON2:
[{"GLComment":"comment from table 2","EnComment":""},
{"GLComment":"","EnComment":""}]
I have tried doing this to append to my existing table
var tblSomething = document.getElementById("table1");
<table class="table 1">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
//table does not get built here only for table 1
<table class="table 2">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
</table>
<script>
//this only works for table1
$(document).ready(function() {
infoTableJson = {}
buildInfoTable();
});
function buildInfoTable(){
$.ajax({ //allows to updates without refreshing
url: "comment1.json", //first json file
success: function(data){
data = JSON.parse(data)
var tblSomething = '<tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td data-key="' + key + '">' + value + '</td>';
});
//tblSomething += '<td><button class="editrow"></button></td>'
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('.table').append(tblSomething)
$('.table td').on('click', function() {
var row = $(this).closest('tr')
var index = row.index();
var comment = row.find('td:nth-child(1)').text().split(',')[0]
var engcomment = row.find('td:nth-child(2)').text().split(',')[0]
var temp1 = row.find('td:nth-child(1)').text().split(',')[0]
var temp2 = row.find('td:nth-child(2)').text().split(',')[0]
var newDialog = $("<div>", {
id: "edit-form"
});
newDialog.append("<label style='display: block;'>GL Comment</label><input style='width: 300px'; type='text' id='commentInput' value='" + comment + "'/>");
newDialog.append("<label style='display: block;'>Eng Comment</label><input style='width: 300px'; type='text' id='engInput' value='" + engcomment + "'/>");
// JQUERY UI DIALOG
newDialog.dialog({
resizable: false,
title: 'Edit',
height: 350,
width: 350,
modal: true,
autoOpen: false,
buttons: [{
text: "Save",
click: function() {
console.log(index);
user = $.cookie('IDSID')
var today = new Date();
var date = (today.getMonth()+1)+'/'+today.getDate() +'/'+ today.getFullYear();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
//FIXME
var comment = newDialog.find('#commentInput').val() + ", <br> <br>" + dateTime + " " + user;
var engcomment = newDialog.find('#engInput').val() + ", <br><br>" + dateTime + " " + user; //it updates both of them no
row.find('td[data-key="GLComment"]').html(comment) //this is what changes the table
row.find('td[data-key="EngComment"]').html(engcomment) //this is what changes the table
// update data
data[index].GLComment = comment;
data[index].EngComment =engcomment;
$.ajax({
type: "POST",
url: "save.asp",
data: {'data' : JSON.stringify(data) , 'path' : 'comments.json'},
success: function(){},
failure: function(errMsg) {
alert(errMsg);
}
});
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}, {
text: "Cancel",
click: function() {
$(this).dialog("close");
$(this).dialog('destroy').remove()
}
}]
});
//$("body").append(newDialog);
newDialog.dialog("open");
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
}
</script>
The "key" here is prebuilt table... And that is a good job for the jQuery .clone() method.
$(document).ready(function() {
// call the function and pass the json url
buildInfoTable("comment1.json");
buildInfoTable("comment2.json");
// Just to disable the snippet errors for this demo
// So the ajax aren't done
// No need to run the snippet :D
$.ajax = ()=>{}
});
function buildInfoTable(jsonurl){
$.ajax({
url: jsonurl,
success: function(data){
data = JSON.parse(data)
// Clone the prebuild table
// and remove the prebuild class
var dynamicTable = $(".prebuild").clone().removeClass("prebuild");
// Loop the json to create the table rows
$.each(data, function(idx, obj){
rows = '<tr>';
$.each(obj, function(key, value){
rows += '<td data-key="' + key + '">' + value + '</td>';
});
rows += '</tr>';
});
// Append the rows the the cloned table
dynamicTable.find("tbody").append(rows)
// Append the cloned table to document's body
$("body").append(dynamicTable)
}
})
}
</script>
/* This class hides the prebuid table */
.prebuild{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This table is a "template" It never will be used but will be cloned -->
<table class="prebuild">
<thead>
<th id = "white">GL Comment</th>
<th id = "white">En Comment</th>
</thead>
<tbody>
</tbody>
</table>

How to create a bootstrap-table dynamically?

I'm having trouble developing a bootstrap-table by clicking a button. My goal is to add a sort feature for each columns on a table. So for my user case, when a user clicks on the button, it calls an ajax to grab a data from Database and sends back a result (it works so no worries on it). So i need to display the results as a bootstrap-table so i can use the sort feature for each column. Plus, I'm using pagination.js which uses Array of json objects and table to display the result.
When I develop the table and append it into a div, I dont see the sort feature on each columns.
It works when I create a simple hard code HTML table with Bootstrap-table attributes such as sort feature (data-sortable="true"). I believe when the page loads bootstrap detects the and its attributs that is on the html body. But when I dynamically create a bootstrap-table, the HTML table is there but not the bootstrap-table feature.
Please help. Here is my code below of how i develop the table using javascript function.
// result is a large string of result when ajax is sending a response.
function displayResult(result) {
//convert the result into Array of JSON
var splitResult = result.split("*split*");
var getLast = splitResult.length - 1;
for(var i = 0; i < splitResult.length; i++){
if(i != getLast) {
splitResult[i] = JSON.parse(splitResult[i]);
} else {
splitResult.splice(i,1);
}
}
// the .pagination is a function that is use in pagination.js
// the #page is a DIV
$('#page').pagination({
dataSource: splitResult,
pageSize: 8,
callback: function(data, pagination) {
// template method
var html = template(data);
// grab the html String and append it into the #demo DIV
$("#demo").append(html);
}
})
}
function template(data) {
// table tag with bootstrap-table attributes
var html = '<table data-toggle="table" style="width: 100%;">';
// create the table headers
html = html + '<thead><tr><th data-field="IDCODE" data-sortable="true">ID</th><th scope="col" data-sortable="true">ZIP 11</th><th scope="col" data-sortable="true">Date</th></tr></thead>'
+ '<tbody>';
// input the results of the data
if (data[0].IDCODE) {
$.each(data, function(index, item) {
html += '<trid="tr-id-2" class="tr-class-2"><td>'
+ item.IDCODE+'</td>'
+ '<td>' + item.ZIP11_ID + '</td>'
+ '<td>' + item.DEL01_TS + '</td></tr>';
});
} else {
$.each(data, function(index, item) {
html += '<tr><td>'+ item +'</td></tr>';
});
}
html += '</tbody></table>';
return html;
}
when using this approach, it just display the html table. Not using bootstrap-table. I'm trying to add a feature where a user can click on the column header to sort.
Hope this code could help you, what it does is
1. display a textBox, where I user can enter a db table name
2. The backend ( in my case Python) get information from db_name_table
3. The data is displayed dinamically in the bootstrap-table
HTML
<form method="GET" id="id1" action="{% url 'request_page' %}">
<input type="text" value="db_name_table" name="mytextbox" id='mytextbox' size="1"/>
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
Javascript:
$(document).ready( function(){
$('#id1').submit( function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success:function( value ){
$('#datatable').bootstrapTable({
striped: true,
pagination: true,
showColumns: true,
showToggle: true,
showExport: true,
sortable: true,
paginationVAlign: 'both',
pageSize: 25,
pageList: [10, 25, 50, 100, 'ALL'],
columns: {{ columns|safe }},
data: {{ data|safe }},
});
}
})
})
});
$(document).ready(function() {
var i = 1;
$('#tab_logic').on('focusout', 'tbody tr:nth-last-child(2) td:nth-last-child(2) input', function() {
if ($(this).val() != '' && $('#tab_logic tbody tr:nth-last-child(2) td:nth-last-child(3) input').val() != "" && $('#tab_logic tbody tr:nth-last-child(2) .product').val() != '') {
b = i - 1;
$('#addr' + i).html($('#addr' + b).html()).find('td:first-child').html(i + 1);
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
$(this).focus().select();
i++;
}
});
$('body').on('click', '#delete_row', function() {
if (i > 1) {
var id = i;
$('#tab_logic tbody tr:nth-last-child(2)').remove();
$('#tab_logic tbody tr:last').attr("id", "addr" + (id - 1));
i--;
}
calc();
});
$('#tab_logic tbody').on('keyup change', function() {
calc();
});
$('#tax').on('focusout', function() {
var total = parseInt($('#sub_total').val());
var tax_sum = eval(total / 100 * $('#tax').val());
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum+total).toFixed(2));
});
});
function calc() {
$('#tab_logic tbody tr').each(function(i, element) {
var html = $(this).html();
if (html != '') {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
$(this).find('.total').val(qty * price);
calc_total();
}
});
}
function calc_total() {
total = 0;
$('.total').each(function() {
total += parseInt($(this).val());
});
$('#sub_total').val(total.toFixed(2));
tax_sum = total / 100 * $('#tax').val();
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum + total).toFixed(2));
}

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

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>

How to generate Dynamic button in a table row and open new page on button click

i actually having a requirement of generating dynamic table from services url and after that generating dynamic table.This is i worked it out but what i want is
How to generate a dynamic button on each table row with click event.
After generating the button how we can assign click events to the button i mean suppose in a table there are four columns like date,id number,name,location and on the clicking on the each column or related to that cell it has to redirect to a new page.
or
if a table row is clicked and there are 4 columns are there like date,id number,name,location the click event has will take date as a parameter and click event function and then it have to proceed to the next page/redirect
$('#btn_Day').click(function () {
var ex = document.getElementById("dpp_info");
var clOptions = ex.options[ex.selectedIndex].value;
var clOptions1 = ex.options[ex.selectedIndex].text;
var dt = todaydate;
var dt1 = todaydate;
$.ajax({
type: 'GET',
url: xxxxx.xxxxx.xxxxx,
data: frmDate_=" + dt + "&toDate_=" + dt1 + "",
success: function (resp) {
var Location = resp;
var tr;
for (var i = 0; i < Location.length; i++) {
tr = tr + "<tr>";
tr = tr + "<td style='height:20px' align='left'>" + Location[i].Name + "</td>";
tr = tr + "<td style='height:20px' align='left'>" + Location[i].Date + "</td>";
tr = tr + "<td style='height:20px' align='left'>" + Location[i].IdNum + "</td>";
tr = tr + "</tr>";
};
document.getElementById('Wise').innerHTML = "<table class='r'>" + "<tr><thead ><th style='height:20px'>Location</th>"
+ "<th style='height:20px'>Date</th>" + "<th style='height:20px'>Id Num</th>" + "</tr></thead>"
+ tr +
"<tr></tr>" +
"</table>";
document.getElementById('Wise').childNodes[0].nodeValue = null;
},
error: function (e) {
window.plugins.toast.showLongBottom("Please Enable your Internet connection");
}
});
});
now in the image if u see there are four columns suppose if i click on the idnumb and there records related to that particular number has to be displayed in separate page
Looking For Help!
After some more discussion on this the key was to just use the handler and pass any values using attributes. You can see the fiddle here
https://jsfiddle.net/p2fpbkuo/3/
$('.button-click').off();
$('.button-click').on('click', function () {
// navigate to new page
// console.log('button click')
// what you could do here is get the serialnumber which is an attribute on the button
var id = $(this).attr('data-id') // as long as this is unique this should always work
var filteredResults = results.filter(function (result) {
if (result.SerialNumber.toString() === id.toString()) {
return result;
}
});
var selectedRowValues = filteredResults[0];
// this will contain all the values for that row
console.log(selectedRowValues)
// var dataValue = $(this).attr('data-url'); // dont't need this any more
window.open(selectedRowValues.Url)
});

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 ?

Categories

Resources