How to SUM cells from DataTables when checked? - laravel

I want to SUM values from cells when I check then. Like:
I´ve found how on DataTables website but it is not quite like I need.
Will be a lot of data on this table, and I want to SUM their values when the checkbox is checked, the save the total on a variable to pass to a controller.
P.S.: I forgot to say that I am using VueJS. Let´s see some code.
#section('scripts')
<script type="text/javascript"
src="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.16/af-2.2.2/b-1.5.1/b-colvis-1.5.1/b-flash-1.5.1/b-html5-1.5.1/b-print-1.5.1/cr-1.4.1/fh-3.1.3/kt-2.3.2/rg-1.0.2/rr-1.2.3/sl-1.2.5/datatables.min.js">
</script>
<script type="text/javascript" src="{{ asset('js/moment-with-locales.min.js') }}"></script>
<script>
var vue = new Vue({
el: '#app',
data: {
isLoading: false,
cliente: '{{ $contemplado->id }}',
checked : false,
nrocpfCnpj: "{!! $contemplado->cpfCnpj !!}",
porte: '{!! $contemplado->porte !!}',
natureza_juridica: '{!! $contemplado->natureza_juridica !!}',
idERP: '{!! $contrato->idERP !!}',
originalSegmento: '{!! $contrato->originalSegmento !!}',
novoSegmento: '{!! $contrato->novoSegmento !!}',
isLoading: false,
grupo: '{!! $contrato->grupo !!}',
cota: '{!! $contrato->cota !!}',
},
mounted() {
const vm = this
var tabela = $('#example').dataTable({
"language": {
'url': '//cdn.datatables.net/plug-ins/1.10.16/i18n/Portuguese-Brasil.json'
},
'scrollX': true,
'scrollY': false,
'autoWidth': true,
responsive: true,
processing: true,
"ajax": {
"url": "montaTabelaMultiCota",
"data": {
"nrocpfCnpj": vm.nrocpfCnpj
}
},
columns: [
{ data: null,
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<div class='form-check'><input class='form-check-input' type='checkbox' name='cota"+oData['NUMERO-COTA']+"' value='"+oData['VALOR-BEM']+"'></div>")
}
},
{ data: 'CODIGO-GRUPO'},
{ data: 'NUMERO-COTA',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html(oData['NUMERO-COTA'])
}
},
{ data: 'DESCRICAO-BEM'},
{ data: 'VALOR-BEM',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("R$ "+oData['VALOR-BEM']+",00")
}
},
{ data: 'NUMERO-CONTRATO'},
{ data: 'DATA-CONTEMPLACAO',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
moment.locale('pt-br');
var data = oData['DATA-CONTEMPLACAO'];
let criado = moment(data, 'YYYYMMDD').fromNow();
$(nTd).html(criado);
}
},
{ data: 'DATA-ENTREGA',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
moment.locale('pt-br');
var data = oData['DATA-ENTREGA'];
let criado = moment(data, 'YYYYMMDD').fromNow();
$(nTd).html(criado);
}
}
]
});
// Adds the values and updates the readonly input.
function updateTotal(){
$('input#total').val($('input.selected:checked').toArray().reduce(function(last, current){
return last + parseInt($(current).attr('data-value'));
}, 0));
}
// init the total value and bind updateTotal function to the change event on the checkboxes.
function dt_init(){
updateTotal();
$('.selected').off('change').on('change', function(e) {
updateTotal();
});
}
var dt = $('#dt_container').DataTable({
// Add the checkboxes and set the values in a data-* attribute for later
rowCallback: function(row, data){
let value = parseInt($('td:eq(4)', row).html().substring(3))
// $('td:eq(4)', row).html() : 'R$ 12975.00'
// 'R$ 12975.00'.substring(3) : '12975.00'
// parseInt('12975.00') : 12975
$('td:eq(0)', row).html(`<input class="selected" type="checkbox" data-value=${value}>`)
},
// If you need to redraw your table (sort, search, page), then you need to redo some things, that's why dt_init is called upon every time.
initComplete: function(settings, json, param){
// show the footer after the DataTable is done
$(dt.table().footer()).css('display', '');
dt_init();
},
drawCallback: function(settings){
dt_init();
}
});
},
});
</script>
#endsection
Any helps?
Thanks a lot!

You can use a footer in your datatable. Just make it initially invisible and add some boilerplate to show some results.
<table id="dt_container">
<tfoot style="display: none;">
<tr>
<th>Total:</th>
<th><input id="total" type="text" name="total" value="" readonly></th>
</tr>
</tfoot>
</table>
Next, in the javascript init the DataTable but add some callbacks
// Adds the values and updates the readonly input.
function updateTotal(){
$('input#total').val($('input.selected:checked').toArray().reduce(function(last, current){
return last + parseInt($(current).attr('data-value'));
}, 0);
}
// init the total value and bind updateTotal function to the change event on the checkboxes.
function dt_init(){
updateTotal();
$('.selected').off('change').on('change', function(e){
updateTotal();
});
}
var dt = $('#dt_container').DataTable({
// Add the checkboxes and set the values in a data-* attribute for later
rowCallback: function(row, data){
let value = parseInt($('td:eq(4)', row).html().substring(3))
// $('td:eq(4)', row).html() : 'R$ 12975.00'
// 'R$ 12975.00'.substring(3) : '12975.00'
// parseInt('12975.00') : 12975
$('td:eq(0)', row).html(`<input class="selected" type="checkbox" data-value=${value}>`)
},
// If you need to redraw your table (sort, search, page), then you need to redo some things, that's why dt_init is called upon every time.
initComplete: function(settings, json, param){
// show the footer after the DataTable is done
$(dt.table().footer()).css('display', '');
dt_init();
},
drawCallback: function(settings){
dt_init();
}
});

Related

Individual column filtering using datatable

My target is to have an individual filtering for column. My reference is: https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html
The problem I am encountering right now when I type, my datatable doesn't do any filtering and it shows an error regarding CURSORPOSITION:
I followed the guide thoroughly and made a lots of research but I still failed to achieve my goal. I hope you can help me
Views:
<table id="example" class="table table-bordered table-hover table-striped is-narrow is-hoverable is-fullwidth text-nowrap" style="width: 100%;">
<thead>
<tr>
<th>TESTING ID</th>
<th>TESTING ACTION</th>
<th>TESTING DESC</th>
<th>TESTING Date</th>
<th>TESTING VENUE</th>
<th>TESTING TICKET</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Ajax:
$(document).ready(function() {
$('#example thead tr')
.clone(true)
.addClass('filters')
.appendTo('#example thead');
table = $('#example').DataTable({
dom: 'lfrtip',
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
orderCellsTop: true,
fixedHeader: true,
initComplete: function () {
var api = this.api();
// For each column
api
.columns()
.eq(0)
.each(function (colIdx) {
// Set the header cell to contain the input element
var cell = $('.filters th').eq(
$(api.column(colIdx).header()).index()
);
var title = $(cell).text();
$(cell).html('<input type="text" placeholder="' + title + '" />');
// On every keypress in this input
$(
'input',
$('.filters th').eq($(api.column(colIdx).header()).index())
)
.off('keyup change')
.on('change', function (e) {
// Get the search value
$(this).attr('title', $(this).val());
var regexr = '({search})'; //$(this).parents('th').find('select').val();
var cursorPosition = this.selectionStart;
// Search the column for that value
api
.column(colIdx)
.search(
this.value != ''
? regexr.replace('{search}', '(((' + this.value + ')))')
: '',
this.value != '',
this.value == ''
)
.draw();
})
.on('keyup', function (e) {
e.stopPropagation();
$(this).trigger('change');
$(this)
.focus()[0]
.setSelectionRange(cursorPosition, cursorPosition);
});
});
},
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('controller/lists')?>",
"type": "POST",
async:true,
dataType: "json",
"data": function(data){
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});

laravel 419 status code (unknown status)

I do an ajax call but I keep getting this error:
419 (unknown status)
i include in meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
my table (without form):
<table class="table" id="dataTables">
<thead>
<tr>
<td>Full nametd>
<td class="text-center">Lớp</td>
<td class="text-center"><input type="checkbox" id="select_all"></td>
</tr>
</thead>
</table>
i use DataTables library load all data from Controller:
var table = $('#dataTables').DataTable({
"pagingType": "full_numbers",
"processing": true,
"serverSide": true,
"lengthMenu": [[5, 10, -1], [5, 10, "All"]],
"iDisplayLength": 5,
"ordering": false,
"ajax": '{!! url(Request::segment(1).'/lists?class_id='.Input::get('class_id')) !!}',
'createdRow': function (row, data, dataIndex) {
$(row).attr('id', data.id);
},
"columns": [
...
{
"data": "id", "sClass": "text-center",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<input type='checkbox' name='check[]' value='" + oData.id + "'>");
}
},
],
"language": {
"url": "{{url('public/extension/datatables/vietnamese.json')}}"
}
});
My Ajax:
$('#save').click(function () {
$.ajax({
type: 'POST',
url: "{{url('class/store')}}",
cache: false,
data: {"check": sThisVal }, //sThisVal get all input checkbox checked
success: function (r) {
$('#msg').html(r);
},
error: function (jqXHR, text, errorThrown) {
$('#msg').html(jqXHR + " " + text + " " + errorThrown);
}
});
});
My route:
Route::post('class/lists', 'ClassController#lists');
My controller method
public function store(Request $request){
var_dump($request->all());exit;
}
Result after click submit is null ???
In addition to putting the crsf-token value in the header meta you need to pass it through in your AJAX requests with something like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
This is from: https://laravel.com/docs/5.6/csrf#csrf-x-csrf-token
I added the crsf-token in the data section on my ajax and it worked like a charm for me.
$('#save').click(function () {
$.ajax({
type: 'POST',
url: "{{url('class/store')}}",
cache: false,
data: {
"check": sThisVal,
"_token": "{{ csrf_token() }}",
}, //sThisVal get all input checkbox checked
success: function (r) {
$('#msg').html(r);
},
error: function (jqXHR, text, errorThrown) {
$('#msg').html(jqXHR + " " + text + " " + errorThrown);
}
});
});
Hope this Helps
sometimes all u need to do to fix this is to make the method post caps like the below

checkbox in vuejs and laravel

I want to generate checkbox using v-for and use v-model. But i am having difficult time trying the get the value of checkbox. Here is what i am doing. My view looks like this:
<div class="checkbox" v-for="role in userRole">
<label>
<input v-model="newUser.urole" type="checkbox"
value="#{{role.roName}}">#{{role.roName}}</label>
</div>
Here is my Vue Js:
var emailRe = /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*#([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i
var vm = new Vue({
el: '#userMgt',
data: {
newUser:{
fname: '',
mname: '',
lname: '',
email: '',
username: '',
password: '',
conpassword: '',
utype: '',
urole:''
},
},
methods: {
fetchUser: function () {
this.$http.get('../api/users', function (data) {
this.$set('users', data)
});
},
fetchUserType: function () {
this.$http.get('../api/usertype', function (data) {
this.$set('userType', data);
});
},
fetchUserRole: function () {
this.$http.get('../api/role', function (data) {
this.$set('userRole', data);
});
},
AddNewUser: function(){
//user input
var user = this.newUser;
alert(user.urole) ///not alerting right info
//clear form input
this.newUser = {fname:'',mname:'',lname:'',email:'',username:'',password:'',conpassword:'',utype:'',urole:''};
this.$http.post('../api/users', user);
;
},
selectAll: function(){
}
},
computed: {
},
ready: function () {
this.fetchUser();
this.fetchUserType();
this.fetchUserRole();
}
});
I am not able to get the selected value in newUser.urole and more over all my checkbox gets selected when i click one. How can i do this?. Thanks

Getting only modified or new Kendo UI Grid rows to send to the server

Although I have tried several times, I could not solve trying many method.
Shortly this is the thing what I want to do : only get modified or new rows as an object or JSON string.
You should use set for changing the content of a record. Then, getting the records modified is just iterating through datasource.data() array and checking which items have dirty set to true.
var data = grid.dataSource.data();
var dirty = $.grep(data, function(item) {
return item.dirty
});
// Dirty array contains those elements modified
console.log("dirty", dirty);
The following snippet shows both that changing the data programmatically or via Grid built-in incell edition is compatible with this approach.
$(document).ready(function() {
var crudServiceBaseUrl = "http://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
Discontinued: { type: "boolean" }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 300,
columns: [
"ProductName",
{ field: "Discontinued", width: 120 }
],
editable: "incell",
selectable: true
}).data("kendoGrid");
$("#change").on("click", function() {
var sel = grid.select();
if (sel.length) {
var item = grid.dataItem(sel);
item.set("Discontinued", true);
}
});
$("#show").on("click", function() {
var data = grid.dataSource.data();
var dirty = $.grep(data, function(item) {
return item.dirty
});
$("#logger").html(JSON.stringify(dirty, null, 2));
});
});
#logger {
min-height: 60px;
border: 1px solid black;
overflow-x: scroll
}
#grid {
width: 500px;
}
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1119/styles/kendo.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1119/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1119/js/kendo.all.min.js"></script>
<div id="example">
<div>
This button changes the Discontinued field to "true" for the selected row:
<button id="change" class="k-button">Change selected</button>
</div>
<div>
Click for displaying modified rows:
<button id="show" class="k-button">Show dirty</button>
<pre id="logger"></pre>
</div>
<div id="grid"></div>
</div>

Refresh jQuery datatable table

Been plenty of questions about this but I never found one that worked for me. I have a plain and simple HTML table whos body is being filled with rows from an AJAX call.
Then I want to update the table with DataTable plugin but it does not work.
I have a HTML table that looks like this:
<table id="myTable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
In my jQuery pageload
$(document).ready(function(){
var oTable = $('#myTable').dataTable({
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
And finally my on dropdownlist change function
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
var oTable = $('#myTable').dataTable(); // Nothing happens
var oTable = $('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
The append and so on has been modified to shorten it down, etc so do not focus too much on it.
Basically the question is how to update the table, I can do my AJAX and add new data to the table fine, but the datatable plugin does not update with it.
I've tried other things like
.fnDraw(false);
But it does nothing
While I get an JSON error from
fnReloadAjax()
Any clues on just how to refresh the table?
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
$('#myTable').dataTable().fnDestroy();
$('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
DEMO
I Know this is an old post, but I've just investigated about the problem and I find the easiest way to solve it in DataTable man pages: https://datatables.net/reference/api/ajax.reload%28%29
All you need to call table.ajax.reload();
var table = $('#product_table').DataTable({
"bProcessing": true,
"serverSide": true,
responsive: true,
"ajax": {
url: get_base_url + "product_table", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function () {
$("#employee_grid_processing").css("display", "none");
}
}
});
//call this funtion
$(document).on('click', '#view_product', function () {
table.ajax.reload();
});
I had done something that relates to this... Below is a sample javascript with what you need. There is a demo on this here: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table
var manageMemberTable;
function updateMember(id = null) {
if(id) {
// click on update button
$("#updatebutton").unbind('click').bind('click', function() {
$.ajax({
url: 'webdesign_action/update.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
}
}
});
}); // click remove btn
} else {
alert('Error: Refresh the page again');
}
}
From version 1.10.0 onwards you can use ajax.reload() api.
var table = $('#myTable').DataTable();
table.ajax.reload();
Keep in mind to use $('#myTable').DataTable() and not
$('#myTable').dataTable()

Resources