datatable scrollX not working properly in dynamic column - javascript

I'm trying to display a lot of columns dynamically from geojson feature.properties in modal. I have successfully displayed it but the problem is when I click next page scrollX didn't work as intended.
Here is my code:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document" style="margin:auto !important;max-width:1080px !important;">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Map Attributes</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalbody_1">
<div class="">
<table id="mapattr" class="display nowrap" style="width:100%" cellspacing="0">
<thead></thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
var dataGSet = [];
var dataGArray;
var columnRef = [];
$.get(url, function(data) {
columnRef = [];
$("#mapattr > thead").append("<tr></tr>");
$.each(data.features, function(a, b) {
var cRow = [];
$.each(b.properties, function(key, value) {
if (a == 0) {
$("#mapattr > thead > tr").append("<td>" + key + "</td>");
columnRef.push({
title: key
})
}
cRow.push(value);
});
dataGSet.push(cRow);
});
}).done(function() {
dataGArray = JSON.parse(JSON.stringify(dataGSet));
if (!$.fn.DataTable.isDataTable('#mapattr')) {
$("#mapattr").DataTable({
dom: 'Bfrtip',
data: dataGArray,
scrollX: true,
buttons: [
'copy', 'csv', 'excel', 'pdf'
]
});
} else {
$('#mapattr').DataTable().destroy();
$('#mapattr').empty();
$("#mapattr").DataTable({
dom: 'Bfrtip',
data: dataGArray,
scrollX: true,
buttons: [
'copy', 'csv', 'excel', 'pdf'
]
});
}
});
</script>
First load:
When I click page 2:
I already tried the table-responsive suggestion from this article but the problem with the user scrolling it, the buttons, page, and search box will also be scrolled so it's a little hassle for the client when they want to navigate in another page.

Related

Fail to load different content in modal Table

I have two bootstrap tables, one of them (table_compras) calls a modal (table_modal) depending on the column clicked, but i am having troubles refreshing the content rows in table, here is my code:
HTML:
<div id="modalTable" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Acumulado por Obra</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="bodyIP">
<table id="table_modal" data-detail-view="true" data-checkbox-header="true" data-search="true"
data-search-align="left" data-detail-filter="detailFilter" data-pagination="true">
<thead id="thDel">
<tr>
</tr>
</thead>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS Here i am getting the row and column index to populate the modal table but when I click on a different cell it continues getting the same data rows of the first cell. I have tried the commented lines of code but none of them give me the desired result :
var $table_compras = $('#table_compras')
var $table = $('#table_modal')
$(function() {
$('#modalTable').on('shown.bs.modal', function () {
$table.bootstrapTable('resetView');
})
$('#modalTable').on('hide.bs.modal', function (e) {
//var table = $('#table_modal').DataTable();
//table.clear();
//$("#table_modal tr").remove();
//$('#table_modal').empty();
//$(e.target).removeData('bs.modal');
$('#table_modal').detach();
//$("#table_modal").empty();
//$("#table_modal thead").remove();
//$('#modalTable').removeData();
})
});
$('#table_compras').on('click-cell.bs.table', function (field, value, row, $el)
{
buildTable2($table, 2, $el.C1, value);
$("#modalTable").modal();
//alert($el.C1+"-"+$el.C2+"-"+$el.C3+"---"+value);
});
function buildTable2($el, cells, ano, mes)
{
var columns = []
var data = []
columns.push({ field: 'C1', title: 'idObra', sortable: true})
columns.push({ field: 'C2', title: 'Nombre', sortable: true})
columns.push({ field: 'C3', title: 'Monto', sortable: true})
columns.push({ field: 'C4', title: '% Participacion', sortable: true})
{% for obra in cobros_por_obra %}
var noMes = parseInt('{{obra.1}}');
noMes = noMes + 1;
if ('{{obra.0}}' == ano && 'C' + noMes == mes)
{
//console.log('C' + noMes, mes);
row = {}
row['C1'] = '{{obra.2}}';
row['C2'] = '{{obra.3}}';
row['C3'] = '$' + Number({{obra.4}}).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
row['C4'] = Number({{obra.4}}).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
data.push(row)
}
{% endfor %}
console.log(data);
$el.bootstrapTable({
columns: columns,
data: data,
detailView: cells > 2,
onExpandRow: function (index, row, $detail) {
/* eslint no-use-before-define: ["error", { "functions": false }]*/
//console.log($detail)
expandTable($detail, cells - 1, row.C1)
}
});
}
Got it work:
Just added:
var $body = $('#bodyIP')
and change all $table for $body:
$('#table_compras').on('click-cell.bs.table', function (field, value, row, $el)
{
buildTable2($body.html('<table data-search="true" data-search-align="left" data-detail-filter="detailFilter" data-pagination="true"></table>').find('table'), 2, $el.C1, value);
$("#modalTable").modal();
//alert($el.C1+"-"+$el.C2+"-"+$el.C3+"---"+value);
});

How to load dynamic content in bootstrap modal

i have create a bootstrap modal but i need the content to be dynamic. Each time i select a different table row, the content of that row should popup. The content inside bootstrap modal is a dynamic table. Is possible to show a simple sample of how by selecting from the row of a table, i can get a dynamic table in the popup modal. Please help. Thanks
while($row = $results->fetch_assoc()): ?>
<tr>
<td class="list-answer"
data-toggle="modal"
href="#content-confirmation">
<?= $row["name"]; ?>
</td>
</tr>
<?php endwhile ?>
<div class="control-popup modal fade" id="content-confirmation"
tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title">Are you sure you wanna do
that?</h4>
</div>
<div class="modal-body">
load dynamic table content.......
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"
data-dismiss="modal">Save</button>
</div>
</div>
</div>
Are you trying to give your table column a link with href ? because it would not work like that.
To your question, there are multiple ways of doing this. I would give the table's row an id and handle the row click or column click event in js code. after that i would get that rows content either with an ajax request or directly from the table's columns.
So your code would look like:
while($row = $results->fetch_assoc()): ?>
<tr data-id="<?= $row["id"]; ?>">
<td class="list-answer">
<?= $row["name"]; ?>
</td>
</tr>
your javascript code:
$(function(){
$(".list-answer").click(function() {
var row_id = $(this).parents('tr').attr('data-id');
get_data(row_id);
$('#my-modal').modal();
});
});
function get_data(row_id) {
//either get data with ajax request or row
//fill modals content with $('#input-field-id').val('vlaue') or .html()
}
$.ajax({
url : 'url',
method : 'post',
data: {
},
success : function(response)
{
$('#my-modal').html(response);
// put your html response in the popup div
$('#my-modal').modal();
}
});
<div id="my-modal"></div>
I don't know if i understand well, but i think you need something like me :
$("table").on('click', 'tr', function() {
var json_data = {
"controller": "NameOfController",
"action": "action",
"contentofRow": $(this).text()
};
$.post('ajax_handler.php', json_data, function (res) {
if (res.indexOf('ERREUR') != -1) {
alert(res);
return false;
}
else {
$('#mymodalID').modal();
$("#myModalLabel").html("Content of the row : " + res[0]);
$.each(res[1], function (index, valeur) {
$("#bodySupp").append($('<tr>')
.css("text-align", "center")
.css("fontSize", "12px")
.append($('<th>')
.html(valeur['indexOfValue'])
)
.append($('<th>')
.html(index)
)
.append($('<th>')
.html(valeur['indexOfValue2'])
)
.append($('<th>')
.html(valeur['indexOfValue3'])
)
)
});
}
}, 'json');
});
$("table").on('click', 'tr', function()
You open the modal on the click on the row of the table,
"contentofRow": $(this).text()
You take the content of the current row, this is what you will display :)
And then you have the controller :
class NameOfController implements AjaxControler {
public function execute($data)
{
switch($data['action']){
default :
$contentRow= $data['yourcontent'];
$res = array();
$res[] = $contentRow
return json_encode($res);
}
}
}
You can do that in OctoberCMS backend. I'll give you a quick example.
I put that in a controller _list_toolbar.htm
<button
href="javascript:;"
data-control="popup"
data-size="large"
disabled="disabled"
data-trigger-action="enable"
data-trigger=".control-list input[type=checkbox]"
data-trigger-condition="checked"
onClick="$(this).popup({ handler: 'onAssignTechnical', extraData: { checked: $('.control-list').listWidget('getChecked') } })"
href="javascript:;"
class="btn btn-default oc-icon-plus">
<?= e(trans('lilessam.maintenancesystem::lang.work_orders.assigntechnical_button')) ?>
</button>
And in the onAssignTechnical() in the controller I'll make a bootstrap modal.
public function onAssignTechnical() {
/** Check if this is even set **/
if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {
foreach($checkedIds as $workorder_checked_id) {
$check_work_order = \Lilessam\Maintenancesystem\Models\WorkOrder::where(['id' => $workorder_checked_id, 'assigned_to_id' => null])->count();
}
/** Check if there's more than one record checked */
if(count($checkedIds) == 1 && $check_work_order != 0):
/**Labels **/
$modal_title = Lang::get('lilessam.maintenancesystem::lang.assign_technical_title');
$assign_label = Lang::get('lilessam.maintenancesystem::lang.assign_label');
$name_label = Lang::get('lilessam.maintenancesystem::lang.assign_modal_name_label');
$action_label = Lang::get('lilessam.maintenancesystem::lang.assign_modal_action_label');
/** Getting all workers IDS by their group id 2 **/
$allWorkers_ids = DB::table('backend_users_groups')->where('user_group_id', 2)->get();
/** Workers Array **/
$workers_array = [];
// Looping to get all workers
foreach($allWorkers_ids as $worker_id) {
//Fetching the user
$worker = User::find($worker_id->user_id);
//Pushing the worker to workers' array
array_push($workers_array, [
'login' => $worker->login,
'first_name' => $worker->first_name,
'last_name' => $worker->last_name,
'id' => $worker->id,
]);
}
#setting the table header
$workers_code = '<div class="control-list list-unresponsive">
<table class="table data" data-control="rowlink">
<thead>
<tr>
<th>'.$name_label.'</th>
<th style="width: 150px"><span>'.$action_label.'</span></th>
</tr>
</thead>
<tbody>';
#Adding workers to the table
foreach($workers_array as $worker_row) {
foreach($checkedIds as $workorder_id):
$workers_code .= '<tr>
<td>
<a href="javascript:;">
'.$worker_row['first_name']." ".$worker_row['last_name'].'
</a>
</td>
<td>
<form method="post" data-request="onAssignNow">
<input type="hidden" name="workorder_id" value="'.$workorder_id.'">
<input type="hidden" name="id" value="'.$worker_row['id'].'">
<button type="submit" class="btn btn-info">'.$assign_label.'</button>
</form>
</td>
</tr>';
endforeach;
}
#Adding Table Fotter
$workers_code .= "</tbody>
</table>
</div>";
#Returning all modal
return '
<div class="control-popup modal fade in" id="content-confirmation" tabindex="-1" role="dialog" aria-hidden="false" style="display: block;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">'.$modal_title.'</h4>
</div>
<div class="modal-body">
<div class="form-group textarea-field span-full" data-field-name="idea" id="Form-field-Idea-idea-groupc" style="height: 395px;
overflow-x: hidden;
margin-bottom: 20px;
overflow-y: scroll;">
<div class="qa-message-list" id="wallmessages">
'.$workers_code.'
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">X</button>
</div>
</div>
</div>
</div>
';
else:
/** Labels **/
$warning_title = Lang::get('lilessam.maintenancesystem::lang.assign_technical_warning_title');
$warning_body = Lang::get('lilessam.maintenancesystem::lang.assign_technical_warning');
#Returning all modal
return '
<div class="control-popup modal fade in" id="content-confirmation" tabindex="-1" role="dialog" aria-hidden="false" style="display: block;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">'.$warning_title.'</h4>
</div>
<div class="modal-body">
<div class="form-group textarea-field span-full" data-field-name="idea" id="Form-field-Idea-idea-groupc" style="height: 395px;
overflow-x: hidden;
margin-bottom: 20px;
overflow-y: scroll;">
<div class="qa-message-list" id="wallmessages">
'.$warning_body.'
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">&#10006</button>
</div>
</div>
</div>
</div>
';
endif;
}
}
Excuse me for the long code but I'm sure It will help you.

Datatables in Bootstrap modal width

In my modal I am trying to put Datatables in there, the problem I'm having is that the width is incorrect, it should be the width of the modal but it is actually like this
My jQuery calling the Datatables
function getValidTags(){
var ruleID = $('.ruleID').val();
var table = $('.valid-tags').DataTable({
"ajax": {
"url": "/ajax/getValidTags.php",
"type": "POST",
"data": {
ruleID: ruleID
},
},
"columnDefs": [{
"targets": 2,
"render": function(data, type, full, meta){
return '<button class="btn btn-default btn-sm" type="button">Manage</button> <button class="btn btn-danger btn-sm">Delete</button>';
}
}]
});
}
My HTML
<!-- Modal where you will be able to add new rule -->
<div class="modal fade validation-list-modal" tabindex="-1" role="dialog" aria-labelledby="LargeModalLabel" aria-hidden="true" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-wide">
<div class="modal-content">
<div class="modal-header modal-header-custom">
<input class="ruleID" type="hidden"></input>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h4 class="modal-title modal-title-main">Create New Rule</h4>
</div>
<div class="modal-body">
<div class="topBar">
<div>
<input type="text" class="validTags inputTextStyling">
</div>
</div>
<table class="table table-striped table-condensed valid-tags">
<thead>
<tr>
<th>Tag Name</th>
<th>Autofixes</th>
<th>Manage</th>
</tr>
</thead>
<tbody class="validTagsTable">
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="saveValidTags">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I find this more appropriate solution,
First make your table width 100%
like this:
<table width="100%" id="datatable"></table>
then initialize your table
$('#datatable').DataTable();
and this this
$(document).on('shown.bs.modal', function (e) {
$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
});
For starters try adding following class to your table element
.dataTableLayout {
table-layout:fixed;
width:100%;
}
It would be good if you could make a fiddle of your code with dummy data for solving your problem.
I dont think the accepted answer is the correct answer. There should be no need at all for altering the CSS. It could cause unexpected issues elsewhere. The problem is, that the container (the modal) not is fully established at the time the dataTable is rendered. Look at columns.adjust() :
var table = $('#example').DataTable({
initComplete: function() {
this.api().columns.adjust()
}
...
})
or
$('.modal').on('shown.bs.modal', function() {
table.columns.adjust()
})
I just added table inside div, assigned width:100%; overflow-x:auto to that div and it worked.

Function to append modal

I have 3 modals that all have the same format and are activated by different onclicks (Create Contact, Update Contact, Delete Contact). I am wanting the modal-title and modal-body to change depending on which button was clicked. How would I go about creating a function that appends the modal content depending on which button was clicked? Thank you for your help!
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Contact Created!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div>
</div>
I have written the JavaScript "BootstrapModel" class for the same purpose.
It also depends on jQuery so don't forget to embed jQuery before using this class.
class is :
var BootstrapModal = (function (options) {
var defaults = {
modalId: "#confirmModal",
btnClose: "#btnClose",
title: "Confirm",
content: "Some bootstrap content",
onClose: function () {
},
onSave: function () {
}
};
defaults = options || defaults;
var $modalObj = $(defaults.modalId);
var hideModal = function () {
$modalObj.modal("hide");
};
var showModal = function () {
$modalObj.modal("show");
};
var updateModalTitle = function (title) {
defaults.title = title;
//$($modalObj).find(".modal-title").eq(0).html(title);
$modalObj.find(".modal-title").eq(0).html(title);
};
var updateModalBody = function (content) {
defaults.content = content;
$modalObj.find(".modal-body").eq(0).html(content);
};
return {
getDefaults: function () {
return defaults;
},
hide: function () {
hideModal();
},
show: function () {
showModal();
},
updateTitle: function (title) {
updateModalTitle(title);
return this;
},
updateBody: function (body) {
updateModalBody(body);
return this;
}
}
});
Usage :
var emailModal = new BootstrapModal({modalId: "#confirmModal"});
emailModal.updateTitle("Mail sent successfully").updateBody("<br/>This box will automatically close after 3 seconds.").show();
// Hide the Modal
emailModal.hide();
HTML Structure for the Modal:
<div class="modal fade" id="confirmModal" role="dialog" aria-labelledby="thankyouModal" aria-hidden="true" style="overflow-y: hidden;">
<div class="modal-dialog" style="padding-top: 225px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="thankyouModal">Thank you</h4>
</div>
<div class="modal-body">
Thank you. We'll let you know once we are up.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The way I got around this is by loading the data in from external files. So you'd have your initial declaration of your modal box (just the surrounding div), and then in each file you have the containing code for the rest of the modal, then use a bit of jQuery to fire them off:
HTML (in main file)
<div class="modal" id="modal-results" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
JQuery
$('#create-contact').click(function(){
e.preventDefault();
$("#modal-results").html('create-contact.html');
$("#modal-results").modal('show');
});

fullcalendar bootstrap modal with external event data

I'm using full calendar with a asp.net MVC 5 application.
When I click a on a empty space I get a modal view for creating a event. This works perfect.
When I click on a event I want to get the event data but also some other data then just the start date end date and description.
I have the following:
eventRender: function (event, element) {
var id = event.id;
element.popover({
placement: 'top',
html: true,
content: '<button id="customers" class="btn btn-default" onclick="KlantenModal(' + id + ')">Klant overzicht</button>',
animation: true
});
}
The function that calls the modal.
function KlantenModal(event) {
$('#klanten #eventId').val(event);
$('#klanten').modal('show');
}
and the bootstrap modal:
<div class="modal fade" id="klanten" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Klanten</h4>
</div>
<div class="modal-body">
/* here I want some Data eg. names of customers */
<input type="hidden" id="eventId" name="eventId" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary"></button>
</div>
</div>
</div>
If i understood you well the only thing you have to do is to add fields to the event like this:
Somewhere in your code populate an array with diferent customers and add that array to the event properties
var customers = [];
customers.push("im customer x");
customers.push("im customer y");
...
events:[
{
'start': 2013-12-30,
'end': 2013-12-30,
'allDay': true,
'customers': customers
}
and when you click on the event and access the event fields you will get the customers field wich contains your customers for that day.

Categories

Resources