I want to remove the columns which have total = 0.
So I've tried in different ways.
First, I assigned ID to all columns, for example; every <td> is of column will have their ID eg: First columns <td ID = 'col_1'> , second column all <td ID = 'col_2'> etc. And then in when footer callback I've tried to remove if this column total is ZERO then this $("col_"+i).remove(); this code removed table headers only so I've tried again with $("col_"+i).empty() but again it's just empty. <th> only
Then I've tried to hide the columns by creating dynamic but I don't get any values.
"footerCallback": function ( row, data, start, end, display )
{
var api = this.api(), data;
var intVal = function ( i ) { return typeof i === 'string' ? i.replace(/[\$,]/g, '')*1 : typeof i === 'number' ? i : 0;};
var col_gonna_invis = '[';
for(i=1;i<length_of_coloumns;i++)
{
total_salary = api.column( i ).data().reduce( function (a, b) {return intVal(a) + intVal(b);},0 );
$('#total_cont_'+i).html(total_salary);
if(total_salary == 0)
{
col_gonna_invis += '{"targets": [ '+i+' ], "visible": false, "searchable": false },';
}
}
col_gonna_invis += ']';alert(col_gonna_invis);
},
"aoColumnDefs": col_gonna_invis;
Please someone help me fix this issue or please someone tell me how to hide or remove columns which footer total is 0.
Thank you in advance.
I will suggest you use the visible() API method along with the sum() plugin :
Enhance the API with a column().sum() method :
jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
return this.flatten().reduce( function ( a, b ) {
if ( typeof a === 'string' ) {
a = a.replace(/[^\d.-]/g, '') * 1;
}
if ( typeof b === 'string' ) {
b = b.replace(/[^\d.-]/g, '') * 1;
}
return a + b;
}, 0 );
} );
now, in initComplete() you can very easy hide columns which have a total or sum() of 0 :
var table = $('#example').dataTable({
//...
initComplete : function() {
var api = this.api(),
colCount = api.row(0).data().length;
for (var i=0; i<colCount; i++) {
if (api.column(i).data().sum() == 0) {
api.column(i).visible(false);
}
}
}
});
demo -> http://jsfiddle.net/qer7e5os/
Related
I'm new to JavaScript.
I creating a table with cells where we can add values and I'm using HandsOnTable.
I need to create an inactive cell and we can't set the value in the inactive cell in HandsOnTable if the previous cell has a value.
It's my code :
<div id="downtimetable"></div>
<script script type="text/javascript" th:inline="javascript">
let dataFromSpringDown = [[${downtimes}]];
let dataObjDown = [];
let temp1 = {
name: ' ',
town: ' ',
tent: ' ',
izoterm: ' ',
ref: ' '
}
for(let obj of dataFromSpringDown){
let object = {
name: obj["name"],
town: obj["town"],
tent: obj["tent"],
izoterm: obj["izoterm"],
ref: obj["ref"]
};
dataObjDown.push(object);
}
dataObjDown.push(temp);
let container2 = document.getElementById('downtimetable');
let hot2 = new Handsontable(container2, {
data: dataObjDown,
rowHeaders: true,
colHeaders: true,
autoWrapRow: true,
colHeaders: [
'Name',
'Town',
'Cost'
],
manualRowMove: true,
manualColumnMove: true,
contextMenu: true,
filters: true,
dropdownMenu: true,
collapsibleColumns: true,
nestedHeaders : [
[
'Name',
'Town',
{
label: 'Cost',
colspan: 3
}
],
[
'','','Tent','Izo','Ref'
]
],
manualColumnResize : true
});
function myFunctionDown() {
var json = JSON.stringify(dataObjDown);
var xhr = new XMLHttpRequest();
xhr.open("POST","/downtime_rows_json");
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(json);
}
</script>
<button onclick="myFunctionDown()" class="btn btn-info">From table</button>
It's a table created with script:
I need to change the status to inactive in cell2 if cell1 has a value and vice versa. How I can do that?
I think we can use this script, but I don't understand how get the previous cell
hot2.updateSettings({
cells: function (row, col, prop) {
var cellProperties = {};
if (hot2.getDataAtRowProp(row, prop) === 'Town1') {
cellProperties.editor = false;
} else {
cellProperties.editor = 'text';
}
return cellProperties;
}
})
The code below will disable cell 2 and delete its value if cell 1 has a value and vice versa. In other words: you can't have values in both column 1 and 2.
hot2.addHook( 'afterChange', function( changes, src ) {
[
[row, prop, oldVal, newVal]
] = changes;
if ( prop == 0 && hot2.getDataAtRowProp( row, prop + 1 ) && newVal?.length > 0 ) {
// delete value of cell 2 if cell 1 has a value
hot2.setDataAtCell( row, prop + 1, '' );
} else if ( prop == 1 && hot.getDataAtRowProp( row, prop - 1 ) && newVal?.length > 0 ) {
// delete value of cell 1 if cell 2 has a value
hot2.setDataAtCell( row, prop -1, '' );
}
})
hot2.updateSettings( {
cells: function ( row, col, prop ) {
cellProperties = {};
if ( prop == 1 && hot2.getDataAtRowProp( row, prop - 1 ) ) {
// this disables cell 2 if cell 1 has a value
cellProperties.readOnly = true;
} else if ( prop == 0 && hot2.getDataAtRowProp( row, prop + 1 ) ) {
// this disables cell 1 if cell 2 has a value
cellProperties.readOnly = true;
} else {
cellProperties.readOnly = false;
}
return cellProperties;
}
})
It's working for me :
hot1.addHook('beforeRenderer', function(td, row, col, prop, value, cellProperties) {
if (prop === 'name') {
var cellMeta = this.getCellMeta(row, this.propToCol('town'));
cellMeta.readOnly = (value != ' ' && value != '' && value != null) ? true : false;
} if (prop === 'town') {
var cellMeta = this.getCellMeta(row, this.propToCol('name'));
cellMeta.readOnly = (value != ' ' && value != '' && value != null) ? true : false;
}
});
You can change the columns name, and it's will still working
I'm trying to do something with JavaScript DataTable but I'm stuck somewhere .
There are 2 DataTable on the same page .
I am sending data from the first DataTable second DataTable . I can write in the footer section that collects in the second DataTable int .
I collect information on hours in a second column in the DataTable I want to write a footer . I could not do it.
How do you think I should proceed . Existing employees script below.
Thank you to everyone.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var t = $('#FlowList').DataTable({
rowReorder: true,
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Tüm sayfaların toplamı
total = api
.column( 3 )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Gösterilen sayfanın toplamı
pageTotal = api
.column( 3, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Footer Güncelleme
$( api.column( 3 ).footer() ).html(
/* '$'+pageTotal +' ( $'+ total +' Toplam)' */
'Toplam ' + total
);
}
});
var counter = 1;
var table = $('#NewsListTable').DataTable();
$('#NewsListTable tbody').on('dblclick', 'tr', function(){
var data = table.row( this ).data();
//alert(data[3]);
t.row.add( [
counter +'', //Sıra numarasını her seferinde 1 arttırıyoruz.
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7],
data[8]
]
).draw( false );
counter++;
});
});
</script>
I can't force to select first row after applied filter. So when I'm loading my page to select first row I use:
gridApi.selection.selectRow($scope.gridOptions.data[0]);
this is from API documentation and it is clear.
Now, I'm trying to select first row after filter.
I have singleFilter function which comes from official documentation
$scope.singleFilter = function( renderableRows ){
var matcher = new RegExp($scope.filterValue);
renderableRows.forEach( function( row ) {
var match = false;
[
'name', 'company', 'email'
].forEach(function( field ){
if (field.indexOf('.') !== '-1' ) {
field = field.split('.');
}
if ( row.entity.hasOwnProperty(field) && row.entity[field].match(matcher) || field.length === 2 && row.entity[field[0]][field[1]].match(matcher)){
match = true;
}
});
if ( !match ){
row.visible = false;
}
});
var rows = $scope.gridApi.core.getVisibleRows();
var first = function(array, n) {
if (array == null){
return void 0;
}
if (n == null) {
return array[0];
}
if (n < 0) {
return [];
}
return array.slice(0, n);
};
console.log(first(rows))
$scope.gridApi.selection.selectRow(first(rows));
return renderableRows;
};
where I get the length of visible rows
var rows = $scope.gridApi.core.getVisibleRows();
thru simple script I get first row
var first = function(array, n) {
if (array == null){
return void 0;
}
if (n == null) {
return array[0];
}
if (n < 0) {
return [];
}
return array.slice(0, n);
};
console.log(first(rows))
then I'm trying to apply selection
$scope.gridApi.selection.selectRow(first(rows));
But unfortunately no success. Where is my mistake? I appreciate any help.
My plunker
I've created a working plunker below.
The reason this is not working is because the visible rows that you are getting is all of the rows, and not just the filtered rows. The reason that is all of the rows is because you are calling for them before returning the filter. I've created logic using what we are knowledgeable about at this point, which is what will be returned once the function completes.
http://plnkr.co/edit/LIcpOs7dXda5Qa6DTxFU
var filtered = [];
for (var i = 0; i < renderableRows.length; i++) {
if (renderableRows[i].visible) {
filtered.push(renderableRows[i].entity)
}
}
if (filtered.length) {
$scope.gridApi.selection.selectRow(filtered[0]);
}
I wrote the code below to search for values in a spreadsheet. For some reason, when I try to search vertically it searches horizontally instead.
I thought that changing valores[cc][0] to valores[0][cc] would do that but it's not working.
Any idea what I am doing wrong?
function onEdit(e){
var a = e.source.getActiveSheet();
var SearchText = "4"
//x = mainSearch( a, 3, 1, "horizontal", SearchText);
x = mainSearch( a, 1, 1, "vertical", SearchText);
}
//mainSearch( targetSheet, row, column, alignment, searchText)
function mainSearch( folha, linha, coluna, procTipo, procTexto) {
if ( procTipo = "horizontal" ) {
var alcance = folha.getRange( linha, coluna, folha.getLastRow(), 1);
}
else if ( procTipo = "vertical" ) {
var alcance = folha.getRange( linha, coluna, 1, folha.getLastColumn());
}
else {
Browser.msgBox("mainSerch com procTipo errado");
}
var valores = alcance.getValues();
for(cc=0;cc<valores.length;++cc) {
if ( procTipo = "horizontal" ) {
Browser.msgBox("Horizontal --> " + valores[cc][0]);
if ( valores[cc][0] == procTexto ) {
return (cc + linha);
}
}
else if ( procTipo = "vertical" ) {
Browser.msgBox("Vertical --> " + valores[0][cc]);
if ( valores[0][cc] == procTexto ) {
return (cc + coluna);
}
}
}
return 0;
}
The problem is here:
if ( procTipo = "horizontal" ) {
When you execute procTipo = "horizontal", you're assigning "horizontal" to procTipo. You should only test its value:
if ( procTipo == "horizontal" ) {
There are three other place where you'll have to change = to ==.
Some people prefer to use === because it doesn't do any type coercion, but in this situation == will work equally well.
You'll have to adjust the iteration limit in order to search through valores properly in the vertical case. Currently you have this:
for(cc=0;cc<valores.length;++cc) {
Replace it with these two lines:
var limit = (procTipo == 'horizontal' ? valores.length : valores[0].length);
for (var cc = 0; cc < limit; ++cc) {
I have a dynamic table in which I can add many rows as needed using jquery.
On this rows there is a select list dropdown. This select has a list.
In function of the selected option, I try to do an ajax request and to apply the result in one of input of this rows.
The trouble I'm actually having is that I can not get the value of the selected list for the concerning rows. I added a class to the select list. The request is happening onchange but it can not get the value of the select list.
below is what I tried :
<script type="text/javascript">
$().ready(function(){
$('.debours_tva').change(function(e){
var debours_id = $(this).closest("tr").find("input.debours_tva").val
console.log(debours_id);
var input = $(this).closest("tr").find("input.taux")
$.ajax({
url: 'requetes_ajax/check_taux_tva_debours.json.php',
method: 'GET',
data: 'debours_id=' + debours_id,
success: function(returnData){
console.log(returnData);
if(returnData !=''){
input.removeAttr('value');
input.attr('value',returnData)
}else{
input.removeAttr('value');
input.attr('value',returnData)
}
},
dataType :'json'
});
});
});
</script>
Actualy the problem met is that line
var debours_id = $(this).closest("tr").find("input.debours_tva").val
that returns the following things instead of its value :
function ( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
Anykind of help will be much appreciated.
You need to replace
.val
by
.val()
The first expression returns the function which is responsible for getting the value. The second will execute it and actually returns the field's value.