How call function component from button render datatable after mounted - javascript

I have a component with version 3 of vue, what I'm trying to do is call a function of my component from the rendering of a datatable column, I just don't know if it's possible. In this case, the function that I am trying to call on the click of a button is editCredential, as it would be done in the template normally. Only this is currently not working for me. What I'm trying to avoid is defining a listener on the table and filtering until I hit the button since I don't like it that much. If anyone knows of a way to do this please help me.
export default{
data() {
return {
credentials:[]
}
},
methods: {
getCredentials(){
jQuery.ajax({
url : window.origin+"/apiadmin/credentialsincludes",
data : {opc:"credentials", action:"getCredentials"},
method : 'post',
dataType:"json",
}).then(resp=>{
this.credentials = resp;
this.generateTable();
}).fail(resp=>{
swal('Ocurrio un problema en la peticion en el servidor, favor de reportar a los administradores', {icon:'error'});
}).catch(resp=>{swal('Ocurrio un problema en la peticion en el servidor, favor de reportar a los administradores', {icon:'error'});});
},
generateTable(){
jQuery('#credenciales').DataTable( {
dom: 'Blfrtip',
data : this.credentials,
"autoWidth": true,
"scrollCollapse": true,
"searching": true,
"paging": true,
"language": {
"emptyTable": "No se encontraron solicitudes registradas"
},
scrollX:"auto",
buttons: [
{
extend: 'excel',
className: 'btn btn-default',
order: [[0, 'asc'], [5, 'asc']],
}
],
"columns": [
{ width:"5%","data": "id_key" },
{ width:"11%","data": "key" },
{ width:"10%","data": "user_key" },
{ width:"10%","data": "nombre_key" },
{ width:"12%","data": "descripcion" },
{ width:"12%","data": "nombre_unidad_negocio" },
{ width:"10%","data": "nombre_cliente" },
{ width:"10%","data": "nombre_producto" },
{ width:"10%","data": "id_key",
render(data, type, data2, key, row) {
// console.log(data, type, data2, key, row);
return (1==1) ? `
<button type="button" #click="editCredential" class="btn animated pull-up btn-warning btn-sm editCredito" data-value=''><i class="la la-edit" style="font-size:11px;"></i></button>
<button type="button" class="btn animated pull-up btn-warning btn-sm editCreditoD" data-key='' data-value=''><i class="la la-trash-alt" style="font-size:11px;"></i></button>` : '';
},
},
],
} );
},
editCredential(){
console.log("hola");
}
},
created() {
setTimeout(() => {
this.getCredentials();
}, 500);
},
components:{
},
template:/* html */`
<div class="row">
<div class="col-12">
<div class="row">
<div class="col-md-2 mb-2">
<button type="button" class="btn btn-block btn-success text-white btn-sm">
Agregar Credenciales <i class="la la-plus"></i>
</button>
</div>
</div>
<div class="row">
<div class="col-md-12 mb-1">
<table class="table table-sm table-striped" style="width:100%;font-size:10px;" id="credenciales">
<thead>
<tr>
<th class="credentials-th">ID</th>
<th class="credentials-th">KEY</th>
<th class="credentials-th">USER</th>
<th class="credentials-th">NOMBRE</th>
<th class="credentials-th">DESCRIPCION</th>
<th class="credentials-th">UNIDAD DE NEGOCIO</th>
<th class="credentials-th">CLIENTE</th>
<th class="credentials-th">PRODUCTO</th>
<th class="credentials-th">ACCIONES</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
`
}
i working with version vue3 and i have segmented for components

Related

datatable with chartjs problem while changing row numbers

I'm trying to integrate datatable with chartjs, it works fine if i dont change the row numbers, or not do any filtration, from UI, when i change the row numbers for example, by default its 10, when i change it to 25, the charts also change, but when i move the mouse cursor to the chartjs canvas sometimes it shows the previous data(the 10 row data). how to fix it, or update the chartjs canvas data to the new
Here is my code:
$(document).ready(function(){
var list_daily_prices = document.getElementById('list_daily_prices')
if(list_daily_prices){
$('#list_daily_prices').DataTable({
"serverSide":true,
"processing":true,
"ordering": false,
"ajax":function(data,callback,settings){
$.get('/prices/daily/data',{
start:data.start,
limit:data.length,
filter:data.search.value,
},function(res){
callback({
recordsTotal:res.length,
recordsFiltered:res.length,
data:res.objects
});
},
);
},
"columns":[
{"data": "counter"},
{"data": function(data,type,dataToSet){
const date = new Date(data.day).toLocaleDateString('fr-CA')
return date
}},
{"data": "total_quantity"},
{"data": "total_price"},
{"data": "income"},
],
"drawCallback":function(settings){
var daily_date = []
var qnt = []
var total_price = []
var income = []
for(counter=0;counter<settings.aoData.length;counter++){
daily_date.push(new Date(settings.aoData[counter]._aData['day']).toLocaleDateString('fr-CA'))
qnt.push(settings.aoData[counter]._aData['total_quantity'])
total_price.push(parseFloat(settings.aoData[counter]._aData['total_price']).toFixed(2))
income.push(parseFloat(settings.aoData[counter]._aData['income']).toFixed(2))
}
var dailyPriceCanvas = $('#list_daily_prices_charts').get(0).getContext('2d')
var dailyPriceData = {
labels: daily_date,
datasets: [
{
label:'quantity',
data: qnt,
backgroundColor : '#9D0CA6',
},
{
label:'total price',
data: total_price,
backgroundColor : '#1392BE',
},
{
label:'income',
data: income,
backgroundColor : '#00a65a',
},
]
}
var dailyPriceOptions = {
responsive : true,
maintainAspectRatio : false,
datasetFill : false,
legend: { display: true },
title:{
display:true,
text:'total daily prices'
},
}
var dailyPriceChart = new Chart(dailyPriceCanvas, {
type: 'bar',
data: dailyPriceData,
options: dailyPriceOptions
})
},
"language":{
search:'',
searchPlaceholder: 'search ',
"paginate":{
'previous':'previous page',
'next':'next page',
},
"lengthMenu": "_MENU_",
"info": "showing _START_ to _END_ total _TOTAL_",
infoFiltered: "",
zeroRecords: "nothing found",
infoEmpty:""
},
dom: 'lBfrtip',
buttons: [
{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible'
},
text:'excel',
},
],
})
}
})
<div class="card">
<section class="content">
<div class="container-fluid">
<div class="row">
<!-- /.col (LEFT) -->
<div class="col-md-12">
<!-- LINE CHART -->
<div class="card card-info">
<div class="card-header">
<h3 class="card-title">chart</h3>
</div>
<div class="card-body">
<div class="chart">
<canvas id="list_daily_prices_charts" style="height:400px; min-height:450px;"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- /.card-header -->
<div class="card-body table-responsive">
<table class="table table-bordered table-striped text-center" id="list_daily_prices" style='width:100%'>
<thead>
<tr>
<th class="">id</th>
<th class="col-2">date</th>
<th class="col-1">quantity</th>
<th class="col-1">price</th>
<th class="col-1">income</th>
</tr>
</thead>
<tbody>
</tbody>
</tfoot>
</table>
</div>
</div>
thank you for your help

Why my design of datatable data is not properly working in JQuery Datatable?

I have following code see my output image my design is scattered everywhere what is the reason behind this.
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary list-panel" id="list-panel">
<div class="panel-heading list-panel-heading">
<button type="button" class="btn btn-default btn-md" data-toggle="modal" data-url="#Url.Action("Create","Group")" id="btnCreateBranch">
<span class="glyphicon glyphicon-new-window" aria-hidden="true"></span> Add Group
</button>
</div>
<div class="panel-body">
<table id="group-data-table" class="table table-striped table-bordered" style="width:100%;">
</table>
</div>
</div>
</div>
My Jquery scripts is:
"columns": [
{ "title": "Group Code", "data": "GroupCode", "searchable": true },
{ "title": "Group Description", "data": "GroupDesc", "searchable": true },
{
"title": "Action",
"data": "GroupCode",
"searchable": false,
"sortable": false,
"render": function (data) {
return 'Edit Delete';
}
}
],
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
});
},
refresh: function () {
dt.ajax.reload();
}
}
my final output is:
My output image
I have solve the problem on my own setting width by using "sWidth": "300px" in all column and problem solve.

validator - unobtrusive form reset not working

I'm using adminlte v 3.0.1. bootstrap
doing some validator and unobtrusive
stuck at resetting form, in example
edit => show modal form => trigger validation => cancel => new => validation result still there
I'm already tried
$('#form').trigger('reset')
~ not doing anything (not triggering anything)
$('#form')[0].trigger('reset') ~ trigger is not a function
document.getElementById('form').reset() ~ not doing anything (not triggering anything)
any help is appreciated
regards
update:
HTML code
#{
ViewBag.Title = "Master Currency";
}
<div class="card-header">
<h3>Currency</h3>
</div>
<div class="card-body">
<div class="row src-form" style="margin-bottom: 15px;">
<div class="col-12">
#{
Html.RenderPartial("_Search");
}
</div>
</div>
<div class="row" style="margin-bottom: 15px;">
<div class="col-1">
<a href="javascript:void(0)" title="Search" id="btn-toggle-search">
<i class="fa fa-search-plus custom-fa"></i>
</a>
</div>
<div class="col-1">
<a href="javascript:void(0)" title="Refresh" id="btn-refresh">
<i class="fa fa-sync custom-fa"></i>
</a>
</div>
<div class="col-1 offset-9">
<a href="javascript:void(0)" id="btn-new" class="btn btn-primary">
<span>New</span>
</a>
</div>
</div>
<div class="row">
<div class="col-12">
<table id="grid">
<thead>
<tr>
<th>Currency Code</th>
<th>Currency Name</th>
<th>Created By</th>
<th>Created Time</th>
<th>Last Modified By</th>
<th>Last Modified Time</th>
<th></th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<div class="modal fade" id="modal-edit">
<div class="curr-edit">
#using (Ajax.BeginForm("Save", "Currency", new { area = "Master" },
new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "curr-edit",
HttpMethod = "POST",
OnSuccess = "successSave",
OnFailure = "failSave"
}, new { #id = "edit-form" }))
{
#Html.AntiForgeryToken()
#Html.Partial("_Edit")
}
</div>
</div>
<div class="modal fade" id="modal-delete">
<div class="curr-del">
#using (Ajax.BeginForm("Delete", "Currency", new { area = "Master" },
new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "curr-del",
HttpMethod = "POST",
OnSuccess = "successDelete",
OnFailure = "failDelete"
}, new { #id = "delete-form" }))
{
#Html.AntiForgeryToken()
#Html.Partial("_Delete")
}
}))
</div>
</div>
The edit form
#model CurrencyModel
#Html.HiddenFor(model => model.CurrencyID, new { #id = "curcy-id" })
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="title-modal"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row" style="margin-bottom: 15px;">
<div class="col-4">
#Html.LabelFor(model => model.CurrencyCode)
</div>
<div class="col-8">
#Html.TextBoxFor(model => model.CurrencyCode, new { #class = "form-control", #id = "curcy-code" })
#Html.ValidationMessageFor(model => model.CurrencyCode, "", new { #class = "validation-message" })
</div>
</div>
<div class="row" style="margin-bottom: 15px;">
<div class="col-4">
#Html.LabelFor(model => model.CurrencyName)
</div>
<div class="col-8">
#Html.TextBoxFor(model => model.CurrencyName, new { #class = "form-control", #id = "curcy-name" })
#Html.ValidationMessageFor(model => model.CurrencyName, "", new { #class = "validation-message" })
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JS Code
$('#grid').DataTable({
'scrollX': true,
'scrollY': true,
'serverSide': true,
'fixedColumns': true,
'sScrolling': true,
'ScrollY': '400px',
'ScrollX': '800px',
'bScrollCollapse': true,
'bSortCellsTop': true,
"sDom": 'Rfrtlip',
"dom": '<"top"i>rt<"bottom"lp><"clear">',
'ajax': {
'url': '#Url.Action("GetCurrency", "Currency", new { area = "Master" })',
'type': 'POST',
'dataType': 'JSON'
},
'columns': [
{ 'data': 'CurrencyCode', 'searchable': true, 'autoWidth': true },
{ 'data': 'CurrencyName', 'autoWidth': true },
{ 'data': 'CreatedBy', 'sortable': false, 'autoWidth': true },
{
'data': 'CreatedTime', 'autoWidth': true, 'sortable': false, 'render': function (jsonDate) {
return convertJsonDate(jsonDate);
}
},
{ 'data': 'LastModifiedBy', 'autoWidth': true, 'sortable': false, 'sortable': false },
{
'data': 'LastModifiedTime', 'autoWidth': true, 'sortable': false, 'render': function (jsonDate) {
return convertJsonDate(jsonDate);
}
},
{
'data': 'CurrencyID', 'width': '50px', 'sortable': false , 'className': 'text-center', 'render': function (data) {
return "Edit"
}
},
{
'data': 'CurrencyID', 'width': '50px', 'sortable': false, 'className': 'text-center', 'render': function (data) {
return "Delete"
}
}
]
});
$(document).ready(function () {
$('#btn-src').click(function () {
var srcparam = $('#src-type').children('option:selected').data('id');
if (srcparam === '' || srcparam === undefined || srcparam === null) {
alert('Pilih kategori pencarian terlebih dahulu!');
return;
}
debugger;
var srcvalue = $('#src-value').val();
if (srcvalue === '' || srcvalue === undefined || srcvalue === null){
alert('Parameter pencarian harus diisi!');
return;
}
oTable = $('#grid').DataTable();
switch (srcparam) {
case 'CODE':
oTable.columns(0).search(srcvalue).draw();
break;
case 'NAME':
oTable.columns(1).search(srcvalue).draw();
break;
}
});
$('#grid').on('click', 'a.btn-edit', function (e) {
var param = parseInt($(this).data('id'));
$.post('#Url.Action("PrepareFormData", "Currency", new { area = "Master" })', { id: param })
.done(function (obj) {
switch (obj.Response) {
case 'SUCCESS':
var validator = $('#edit-form').validate();
validator.resetForm();
$('#edit-form').trigger('reset');
$('#curcy-id').val(obj.Currency.CurrencyID).trigger('change');
$('#curcy-code').val(obj.Currency.CurrencyCode).trigger('change');
$('#curcy-name').val(obj.Currency.CurrencyName).trigger('change');
$('#title-modal').text('Edit Currency');
$('#modal-edit').modal('show');
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg);
break;
}
});
});
$('#grid').on('click', 'a.btn-delete', function (e) {
var param = parseInt($(this).data('id'));
$.post('#Url.Action("PrepareFormData", "Currency", new { area = "Master" })', { id: param })
.done(function (obj){
switch (obj.Reponse) {
case 'SUCCESS':
$('#delete-form').trigger('reset');
$('#curcy-id').val(obj.Currency.CurrencyID).trigger('change');
$('#modal-delete').modal('show');
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg);
break;
}
});
});
$('#btn-new').click(function () {
$.post('#Url.Action("PrepareFormData", "Currency", new { area = "Master" })', { id: 0 })
.done(function (obj) {
switch (obj.Response) {
case 'SUCCESS':
$('#edit-form').trigger('reset');
$('#curcy-id').val(obj.Currency.CurrencyID).trigger('change');
$('#title-modal').text('New Currency');
$('#modal-edit').modal('show');
break;
case 'WARNING':
toastr.warning(obj.ResponseMsg);
break;
case 'ERROR':
toastr.error(obj.ResponseMsg);
break;
}
})
});
});
The issue might be there if you are trying to reset the form when the form is not present in DOM.
Try to reset the form on a Modal open event like this. For example idEditModal is the id of your modal.
$('#idEditModal').on('shown.bs.modal', function (e) {
var $alerts = $('#form');
$alerts.validate().resetForm();
$alerts.find('.error').removeClass('error');
})

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

Bootstrap Data Table Overlap

I have this 2 data tables below as you can see one of them is overlapping the data table and the other one is need to edit the width. I try to add width but don't have any effect on my first data table. Any suggestion about this two problems?.
HTML
<div class="row">
<div class="col-lg-6">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-lg-6">
<i class="fa fa-list fa-fw"></i>Borrower Name
</div>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="dataTable_wrapper">
<div class="col-lg-6">
<table class="table table-striped table-bordered table-hover table-responsive nowrap"
role="grid" style="width: 100%;" id="dtBorrowerName">
</table>
</div>
</div>
</div>
</div>
</div>
#*</div>
<div class="row">*#
<div class="col-lg-6">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-lg-6">
<i class="fa fa-list fa-fw"></i>Book
</div>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="dataTable_wrapper">
<div class="col-lg-6">
<table class="table table-striped table-bordered table-hover table-responsive nowrap"
role="grid" style="width: 10%;" id="dtBook">
</table>
</div>
</div>
</div>
</div>
</div>
</div>
JS CODE
var dtBorrowerName = $('#dtBorrowerName').DataTable({
responsive: true,
processing: true,
info: true,
search: true,
stateSave: true,
order: [[1, "desc"]],
lengthMenu: [[5, 10, 20, -1], [5, 10, 20, "All"]],
ajax: { "url": "/LS/GetBorrower" },
columns:
[
{ data: "BorrowerID", title: "", visible: false, searchable: false },
{ data: "IDNo", title: "ID Number" },
{ data: "Name", title: "Complete Name", sClass: "alignRight", width: " 100px" },
{ data: "BookTransactionHdrID", title: "BookTransactionHdrID", visible: false, searchable: false }
]
});
function GetStudentBook(getId) {
if (getId != 0 || getId != undefined || getId != "") {
dtStudBook = $('#dtBook').DataTable({
responsive: true,
processing: true,
info: true,
retrieve: true,
destroy: true,
search: true,
stateSave: true,
lengthMenu: [[5, 10, 20, -1], [5, 10, 20, "All"]],
ajax: {
"url": "/LS/GetStudentBook",
"data": function (d) {
d.BookTransactionDtlID = getId;
}
},
columns:
[
{ data: "BookId", title: "", visible: false, searchable: false },
//{ data: "Barcode", title: "Barcode", searchable: false },
{ data: "Author", title: "Author" }
// { data: "Title", title: "Title", sClass: "alignRight" },
// { data: "DatePublish", title: "Date Publish", sClass: "alignRight" },
// { data: "PlacePublish", title: "Place Publish" },
// { data: "NameOfPublisher", title: "Name Of Publisher"},
// { data: "ISBN", title: "ISBN"},
// { data: "BookTransactionDtlID", title: "", visible: false }
]
});
}
else {
//do nothing..
}
}
I hit this problem. It is caused by the length of the table headers and the padding around them. (I am assuming that it looks OK if the panel is wide?).
The solution is to write complicated JS to split words like "Publisher" or (as I did in the end) use Bootstrap visibility to show normal words on larger screens and use abbreviations on smaller screens (I found I had to write extra media queries to clean this up).
You may need a tooltip or whatever to explain your abbreviations. You are rather trying to fit a quart into a pint pot (that is a lot of headings for a small panel if you want them orderable etc) I think it will take quite a bit of hand crafting with very specific media queries.
Hope that helps.

Categories

Resources