php product comparison table - javascript

I'm working on a product comparison table. I want to add a td in every last child in all tr. I want to display all products in vertical in a table. The product comparison table is made using php.
This is the code:
<thead id="table_row">
<tr id="h_td">
<th></th>
<th>product 2</th>
<th>product 3</th>
<th>product 2</th>
<th>add</th>
</tr>
</thead>
<tbody id="pro_table">
<tr class="visible-xs " aria-hidden="true" id="collapse" >
<td colspan="5" >Fature 1</td>
</tr>
<tr id="h_td">
<td>Fature 1</td>
</tr>
<tr class="visible-xs" aria-hidden="true" id="collapse">
<td colspan="5">Fature 2</td>
</tr>
<tr id="h_td">
<td>Fature 2</td>
</tr>
<tr class="visible-xs" aria-hidden="true" id="collapse">
<td colspan="5">Fature 3</td>
</tr>
<tr id="h_td">
<td>Fature 3</td>
</tr>
<tr class="visible-xs" aria-hidden="true" id="collapse">
<td colspan="5">Fature 4</td>
</tr>
<tr id="h_td">
<td>Fature 4</td>
</tr>
</tbody>
<?php
$con = mysqli_connect("localhost","root","","COMPARES");
$b_title = array();
$sql="SELECT * from brands";
$run=mysqli_query($con,$sql);
$num_row=mysqli_num_rows($run);
while($row=mysqli_fetch_assoc($run)){
$rows[] = $row;
foreach($rows as $row){
$b_title =$row['brand_id'];
$b_title =$row['brand_title'];
$data =' '.$b_title.' ';
}
}
?>
<script type="text/javascript">
var tables = document.getElementsByTagName('tbody');
var table = tables[tables.length - 1];
var rows = table.rows;
for(var i = 0, td; i < rows.length; i++ ){
td = document.createElement('td');
td.appendChild(document.createTextNode("<?php echo data ?>"));
rows[i].insertBefore(td, rows[i].lastChild);
}
</script>
This is the result:

Why write you own table when much better options out there already exist?
Using jQuery # http://jquery.com/ and DataTables # https://datatables.net/, you can easily have dynamic column adding capability -- Check out this fiddle for an example: http://jsfiddle.net/4nil/zq7j97c4/10/--
var data_table, row_num, col_num, row_cell, col_cell, iter=0;
var cols = [
{ "mDataProp": "Field1"},
{ "mDataProp": "Field2" },
{ "mDataProp": "Field3" },
{ "mDataProp": "Field4" }
];
var colDef = [{aTargets: [0], sTitle: "Date"},
{aTargets: [1], sTitle: "Number"},
{aTargets: [2], sTitle: "FName"},
{aTargets: [3], sTitle: "LName"},
];
//Get stored data from HTML table element
var results = [{
Field1: "2011/04/23",
Field2: 8,
Field3: "Adam",
Field4: "Den"},
{
Field1: "2011/03/25",
Field2: 6,
Field3: "Honey",
Field4: "Singh"}
];
function initDT(){
//Construct the measurement table
data_table = $('#example').dataTable({
"bJQueryUI": true,
//"sPaginationType": "full_numbers",
//"bProcessing": true,
"bDeferRender": true,
"bInfo" : false,
"bDestroy" : true,
"bFilter" : false,
"bPagination" : false,
"aaData": results,
"aoColumns": cols,
"aoColumnDefs": colDef
});
attachTableClickEventHandlers();
}
initDT();
function attachTableClickEventHandlers(){
//row/column indexing is zero based
$("#example thead tr th").click(function() {    
col_num = parseInt( $(this).index() );
console.log("column_num ="+ col_num );  
});
$("#example tbody tr td").click(function() {    
col_cell = parseInt( $(this).index() );
row_cell = parseInt( $(this).parent().index() );   
console.log("Row_num =" + row_cell + "  ,  column_num ="+ col_cell );
});
};
$("#btnAddRow").click(function(){
//adding/removing row from datatable datasource
var record = {
"Field1": "2011/04/23",
"Field2": '8',
"Field3": "tom",
"Field4": "jerry"};
data_table.fnDestroy();
results.push(record);
//results.pop();
initDT();
$('#example').dataTable().makeEditable({
sUpdateURL: function(value, settings) {
console.log(value);
}});
});
$('#btnAddCol').click(function () {
var oSettings = data_table.fnSettings();
$("#example thead tr th").eq(col_num).after('<th></th>');
cols.push( {"mDataProp": "Field5"} );
colDef.push({aTargets: [4], sTitle: "Message"});
results[0].Field5 = "Msg1";
results[1].Field5 = "Msg2";
data_table.fnDestroy();
data_table.oApi._fnAddColumn(oSettings,null);
initDT();
});
EDIT:
If your content is going to be static, there are plenty of "comparison table" examples, using Bootstrap found here: https://bootsnipp.com/tags/table

Related

datatable column filtering with serverside(ajax) doesn't work (with django)

I'm developing with django and javascript with datatable.
I want to apply column filtering in my datatable
(https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html)
but it works fine without serverside option & ajax (in client side),
but it doesn't work with serverside option & ajax.
How can i FIX IT? Please help me..
this is my code.
<table id="sample_table" class="table table-bordered table-hover">
<thead>
<tr>
<th class="sample_id">ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</thead>
<tbody id="sample_table_body">
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>date</th>
<th>serial</th>
<th>name</th>
<th>birth</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
var column_list = [
{ "data" : "id" , "className": "sample_id"},
{ "data" : "receiving_at" },
{ "data" : "serialnumber" },
{ "data" : "name" },
{ "data" : "birthday" },
];
$('#sample_table tfoot th').each(function(){
var title = $("#sample_table thead th").eq( $(this).index() ).text();
$(this).html('<input type="text" placeholder="Search '+title+'" />' );
});
var sample_table = $('#sample_table').DataTable({
"paging": true,
"autoWidth": false,
"lengthChange": false,
"ordering": true,
"processing" : true,
"columns": column_list,
"order": [ [0, 'desc'] ],
"fixedHeader": true,
"orderCellsTop": true,
"ajax": {
url: '/view_datatable/',
type: 'POST'
},
"serverSide" : true, //get data from server
"initComplete": function() { // column filtering RUN after table loaded .
$( '#sample_table tfoot input' ).on( 'keyup change clear', function () {
if ( sample_table.search() !== this.value && this.value.length>0) {
search_result = sample_table.search( this.value );
search_result.draw();
}
} );
}
});
#view.py
def list_datatable(request, companyname):
context = {}
if(request.method == "POST"):
start_page = int(request.POST['start'])
order_direction = request.POST["order[0][dir]"] # direction of ordering(asc, desc)
order_col_no = request.POST["order[0][column]"] # number of index to sort
order_col_name = request.POST['columns[' + str(order_col_no) + '][data]'].strip() # name of colum of ordering
sample_list_all = Sample.objects.all().order_by(order_col_name)
sample_list_per_page = []
for idx, obj in enumerate(sample_list_all[start_page:start_page + 10]):
data = {}
data['id'] = obj.id
data['receiving_at'] = str(obj.receiving_at)
data['birthday'] = obj.birthday
data['serialnumber'] = obj.serialnumber
data['name'] = obj.name
sample_list_per_page.append(data)
#-- end of --#
datalist_to_json = json.dumps(
{"data": sample_list_per_page, "recordsFiltered": len(sample_list_all), "recordsTotal": len(sample_list_all)}
)
return HttpResponse(datalist_to_json, content_type="application/json")

Two footers not printed in pdf and excel format when clicked in button in jquery datatable

Actaullay I have buttons to save in pdf and excel format.I have two footers coming from json as Total and Percentage.When i click the Button then only Total footer is coming but the Percentage row is not coming in the pdf and excel files.I need to show both the footer but it is not coming.
<table id="report46Table" class="display responsive nowrap" style="width: 100%">
<thead>
<tr>
<th>Disturbance</th>
<th>Zero</th>
<th>Minor</th>
<th>Medium</th>
<th>Major</th>
<th>Total</th>
<th>Occurance</th>
</tr>
</thead>
<tfoot>
<tr id="fTotal">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr id="fPercentage">
<th>Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
script to load the datatable is:
<script>
$(document).ready(function() {
var report46Data = [];
var report46Footer = null;
var report46Table = $('#report46Table').DataTable({
data : report46Data,
dom: 'Bfrtip',
buttons: [
'copy',
{
extend: 'excel',
footer: true,
text : 'Export to Excel',
messageTop: 'Records of forest disturbances in the forest',
filename: function(){
return 'report46';
},
},
{
extend: 'pdfHtml5',
footer: true,
//orientation : 'landscape',
pageSize: 'TABLOID',
text : 'Export to Pdf',
messageTop: 'Records of forest disturbances in the forest',
title: '',
filename: function(){
return 'report46';
},
},
],
ordering: false,
"paging" :false,
columns : [ {
"data" : "disturbanceName"
}, {
"data" : "iZero"
}, {
"data" : "iMinor"
}, {
"data" : "iMedium"
} ,{
"data" : "iMajor"
},{
"data" : "total"
},{
"data" : "occurance"
}],
"footerCallback" : function(row, data, start, end, display) {
var api = this.api();
if (report46Footer) {
$($("#fTotal")[0].cells[0]).html(report46Footer[0].disturbance);
$($("#fTotal")[0].cells[1]).html(report46Footer[0].iZero);
$($("#fTotal")[0].cells[2]).html(report46Footer[0].iMinor);
$($("#fTotal")[0].cells[3]).html(report46Footer[0].iMedium);
$($("#fTotal")[0].cells[4]).html(report46Footer[0].iMajor);
$($("#fTotal")[0].cells[5]).html(report46Footer[0].total);
$($("#fTotal")[0].cells[6]).html("");
$($("#fPercentage")[0].cells[0]).html(report46Footer[1].disturbance);
$($("#fPercentage")[0].cells[1]).html(report46Footer[1].iZero);
$($("#fPercentage")[0].cells[2]).html(report46Footer[1].iMinor);
$($("#fPercentage")[0].cells[3]).html(report46Footer[1].iMedium);
$($("#fPercentage")[0].cells[4]).html(report46Footer[1].iMajor);
$($("#fPercentage")[0].cells[5]).html(report46Footer[1].total);
$($("#fPercentage")[0].cells[6]).html("");
}
}
});
$.ajax({
url : A_PAGE_CONTEXT_PATH + "/api/report46/all",
method : "GET",
dataType : "json",
success : function(response) {
report46Data = response.dataList;
report46Footer = response.footer;
report46Table.rows.add(report46Data).draw();
}
});
});
</script>

How to use index column for multiple tables with a single statement in datatable js?

I'm using datatable js for 2 tables in a single page.
HTML
<!-- Table#1 -->
<table class="dataTable">
<thead>
<tr>
<td>#</td>
<td>col1</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>val1</td>
</tr>
<tr>
<td></td>
<td>val2</td>
</tr>
<tr>
<td></td>
<td>val3</td>
</tr>
</tbody>
</table>
<!-- Table#2 -->
<table class="dataTable">
<thead>
<tr>
<td>#</td>
<td>col1</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>val1</td>
</tr>
<tr>
<td></td>
<td>val2</td>
</tr>
<tr>
<td></td>
<td>val3</td>
</tr>
</tbody>
</table>
Javascript
$(document).ready(function() {
var t = $('table.dataTable').DataTable( {
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]]
} );
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
});
It's showing the index column only in first table.
How can I display it?
I know it's possible by using two different id on the tables. But, in that case I've to copy the javascript code again. If I want to use another table need to copy it once more.
Is there any way to use it for all tables by using the javascript code once?
Presumably you want the two tables to be numbered independently of each other.
If so, then this in the event handler should refer to whichever table the event relates to, and t.table(this) will select "this" table from the tables held in t.
$(document).ready(function() {
var t = $('table.dataTable').DataTable({
"columnDefs": [{
"searchable": false,
"orderable": false,
"targets": 0
}],
"order": [[1, 'asc']]
});
t.on('order.dt search.dt', function () {
t.table(this).column(0, {search:'applied', order:'applied'}).nodes().each(function (cell, i) {
cell.innerHTML = i+1;
});
}).draw();
});
Try this,
Use the .eq() method in order to access a jQuery object by its index. And eq indices start from 0.
var numTables = $(table).length
$(document).ready(function() {
for(var i =0; i < numTables; i++){
var t = $('table.dataTable').eq(i).DataTable( {
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]]
} );
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
}
});

jquery datable add checkbox for object initialised table

I am trying to get a checkbox column added to the jQuery datable, however am unable to do so.
My data table is initialised with a JSON object data and I want to add a column of checkboxes before the data. The data table shows the data but not check box column. The relevant code is as follows
HTML
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Request ID</th>
<th>Request Date</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
</tr>
</thead>
</table>
JAVASCRIPT CODE
msg = $.parseJSON(msg);
console.log(msg);
$('#mytable').DataTable({
data: msg,
columns: [
{ data: 'RequestID' },
{ data: 'RequestDate' },
{ data: 'LeaveType' },
{ data: 'LeaveStart' },
{ data: 'LeaveEnd' },
{ data: 'Status' }
],
"columnDefs": [ {
"targets": 0,
"searchable": false,
"data": null,
"defaultContent": "<button>Click!</button>"
}]
});
PHP CODE TO GET DATA FROM MYSQL DATABASE
$result = $conn->query($sql);
//$result = $result->num_rows;
if($result->num_rows >0){
$res = array();
while($row =mysqli_fetch_assoc($result))
{
$res[] = $row;
}
//$res = array( "data"=>$res);
$output = json_encode($res);
} else
{
$output = 'fail';
}
echo $output;
die();
I have searched through the forums but all of the results i get are for ajax sourced data and not ones populated like I do.
Regards,
You can try this:
HTML
<table id="mytable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th><input type="checkbox" name= "check_all" id="check_all" value="1" /></th>
<th>Request ID</th>
<th>Request Date</th>
<th>Leave Type</th>
<th>Start Date</th>
<th>End Date</th>
<th>Status</th>
</tr>
</thead>
Javascript:
msg = $.parseJSON(msg);
$('#mytable').DataTable({
data: msg,
columns: [
{ data: 'RequestID' },
{ data: 'RequestDate' },
{ data: 'LeaveType' },
{ data: 'LeaveStart' },
{ data: 'LeaveEnd' },
{ data: 'Status' }
],
"columnDefs": [ {
"targets": 0,
"searchable": false,
"data": "RequestID",
"render": function ( data, type, full, meta ) {
return '<input type="checkbox" name= "check_id[]" data-id="'+data+'" />';
},
}]
});

Cannot destroy() using "Yet Another DataTables Column Filter" plugin

I'm using DataTables and YADCF to filter a table.
At some point, I need to temporarily unbind both plugins from my table and later bind them again. If I don't use YADCF, I can destroy the datatable and initialise it again. However, when I use YADCF, the filter part of the table isn't destroyed.
HTML:
Create | Destroy
<table id="mytable" class="results table table-striped">
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
<th>Head 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>152</td>
<td>13</td>
<td>154</td>
</tr>
<tr>
<td>1762</td>
<td>1873</td>
<td>1874</td>
</tr>
<tr>
<td>124</td>
<td>1343</td>
<td>1124</td>
</tr>
</tbody>
</table>
JS without YADCF JSFIDDLE:
var oTable = $('table');
$('#create').click(function (e) {
e.preventDefault();
oTable.dataTable({
"bJQueryUI": true,
"bStateSave": true,
"bPaginate": false,
"bAutoWidth": false,
});
});
$('#destroy').click(function (e) {
e.preventDefault();
oTable.fnDestroy();
oTable.attr('class', '');
});
JS with YADCF JSFIDDLE:
var oTable = $('table');
$('#create').click(function (e) {
e.preventDefault();
oTable.dataTable({
"bJQueryUI": true,
"bStateSave": true,
"bPaginate": false,
"bAutoWidth": false,
});
// Add YADCF
oTable.yadcf([{
column_number: 1,
filter_type: 'range_number',
ignore_char: 'm'
}, {
column_number: 2,
filter_type: 'text',
filter_default_label: ' '
},
]);
});
$('#destroy').click(function (e) {
e.preventDefault();
oTable.fnDestroy();
oTable.attr('class', '');
});
Can anyone suggest how to destroy the YADCF filter too?
So, this is actually a bug present.
Issue Submitted | Workaround JSFiddle
JS:
var oTable = $('table');
var first = true;
$('#create').click(function (e) {
e.preventDefault();
oTable.dataTable({
"bJQueryUI": true,
"bStateSave": true,
"bPaginate": false,
"bAutoWidth": false
});
if (first) {
first = false;
// Add YADCF
oTable.yadcf([{
column_number: 1,
filter_type: 'range_number',
ignore_char: 'm'
}, {
column_number: 2,
filter_type: 'text',
filter_default_label: ' '
} ]);
} else {
oTable.find('thead').find('[id^=yadcf-filter-wrapper-table]').each(function (i, v) {
var cloned = $(this).clone(true);
console.log( $(this) );
$(this).closest('th').append( cloned );
$(this).remove();
oTable.find('.DataTables_sort_wrapper').css('display', 'inline-block');
});
oTable.find('[id^=yadcf]').show();
}
});
$('#destroy').click(function (e) {
e.preventDefault();
oTable.fnDestroy();
oTable.attr('class', '');
oTable.off();
oTable.find('[id^=yadcf]').hide();
oTable = $('table');
});
$('#add-row').click(function (e) {
e.preventDefault();
$('table').append('<tr><td>' + getRandom() + '</td><td>' + getRandom() + '</td><td>' + getRandom() + '</td></tr>');
});
function getRandom() {
return parseInt(10000 * Math.random(), 10);
}
try the below:
$('#destroy').click(function (e) {
e.preventDefault();
oTable.Destroy();
oTable.attr('class', '');
});

Categories

Resources