How to create a bootstrap-table dynamically? - javascript

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

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 fetch image form its path given in the csv file to create HTML table?

I wanted the HTML table to show a specific image from its path given in the file.
csv file:
HTML Page output:
HTML code which I'm currently using.
<script>
function arrayToTable(tableData) {
var Table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return Table;
}
$.ajax({
type: "GET",
url: "./img.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
I applied this script because every time I will have a variable number of rows and columns, but how to modify this script so that it will read the image address given in the col 3 and fetch those images from their path and put them in the table.
If the image is always going to be in the third column, you could do something like this.
i !== 0 is telling the browser to ignore the first row.
j === 2 is telling the browser to render the third column differently.
If the image won't always be in column 3 you could parse each string value and see if it is a image URL, but if this works it works.
if (i!==0 && j===2) {
row.append($("<td><img src='" + cellData + "'/></td>"));
return
}
});
function arrayToTable(tableData) {
var table = $("<table></table>");
$(tableData).each(function (i, rowData) {
var row = $("<tr></tr>");
$(rowData).each(function (j, cellData) {
if (i!==0 && j===2) {
row.append($("<td><img src='" + cellData + "'/></td>"));
return
}
row.append($("<td>" + cellData + "</td>"));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "./img.csv",
success: function (data) {
$("body").append(arrayToTable(Papa.parse(data).data));
}
});
give an id to your table:
var Table = $('<table id="my-table"></table>');
then create an image element with the address you already have in the cell:
$('#my-table tr').each(function( index ) {
var img_url = $( this ).children("td:last").text();
var img_element = $(document.createElement('img'))
img_element.attr('src', img_url);
$( this ).children("td:last").html(img_element);
});
Below you can run an example with sample data:
function arrayToTable(tableData) {
var table = $('<table id="my-table"></table>');
$(tableData).each(function(i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function(j, cellData) {
row.append($('<td>' + cellData + '</td>'));
});
table.append(row);
});
return table;
}
$('body').append(arrayToTable([["asdf","qwer","https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"]]));
$('#my-table tr').each(function( index ) {
var img_url = $( this ).children("td:last").text();
var img_element = $(document.createElement('img'))
img_element.attr('src', img_url);
$( this ).children("td:last").html(img_element);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

checkboxes and number fields set by jquery appear for a split second, then suddenly disappear

I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle

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