SyntaxError: missing ) after formal parameters when adding if/else - javascript

Can anyone tell me what i am doing wrong , i want to have different views for different users in handsontable.I am defining the table as
document.addEventListener("DOMContentLoaded", function() {
var create_table = document.getElementById('create_table');
var mydata = document.getElementById('mydata').innerHTML;//to get the hidden element
var logged_user = document.getElementById('logged_user').innerHTML;// to get remote user
var plan_creator = document.getElementById('plan_creator').innerHTML;//to get the person who has created the plan
console.log(logged_user + " " + plan_creator);
console.log(mydata);
var searchResultCount=0;
var hot,searchFiled,resultCount;
function searchResultCounter(instance, row, col, value, result) {
Handsontable.plugins.Search.DEFAULT_CALLBACK.apply(this, arguments);
if (result) {
searchResultCount++;
}
}
var buttons = {
save:document.getElementById('save'),
load:document.getElementById('load'),
file:document.getElementById('file_export')
}
var objectData = JSON.parse(mydata);//to decode data in JSON format
console.log(objectData);
hot = new Handsontable(create_table, {
data:objectData,
colHeaders: true,
rowHeaders: true,
contextMenu: true,
minRows: 30,
minCols: 13,
maxCols:18,
maxRows:100,
copyPaste:true,
dropdownMenu: true,//plugin to display menu on column header
filters:true,
columnSorting:true,//plugin to enable sorting
sortIndicator:true,//to display sorting is done
comments:true,//to add comments
colHeaders:["Testcase Name","Cell Name","Customer","Flops","Title","Status","Mfix CCR","Scenerio Brief Description","Expected Results","CCR Status","CCR No","Remarks","Testcase Path"],
if(logged_user == plan_creator) {
columns:[//when using this not able to remove column
{data:'tc_name'},
{data:'cell_name'},
{data:'customer_name'},
{data:'flops' ,type:'numeric'},
{data:'title'},
{data:'status'},
{data:'mfix_ccr'},
{data:'test_scenerio'},
{data:'expected_results'},
{data:'ccr_status'},
{data:'ccr_num'},
{data:'remarks'},
{data:'tc_path'}],
}
else{
columns:[//when using this not able to remove column
{data:'tc_name' ,readOnly:true } ,
{data:'cell_name',readOnly:true },
{data:'customer_name',readOnly:true },
{data:'flops' ,type:'numeric',readOnly:true },
{data:'title',readOnly:true },
{data:'status',readOnly:true },
{data:'mfix_ccr',readOnly:true },
{data:'test_scenerio',readOnly:true },
{data:'expected_results',readOnly:true },
{data:'ccr_status',readOnly:true },
{data:'ccr_num',readOnly:true },
{data:'remarks'},//only remarks can be added by other user
{data:'tc_path',readOnly:true }],
}
search: {
callbak:searchResultCounter
}
});
searchFiled = document.getElementById('search_filed');
resultCount=document.getElementById('resultCount');
var exportPlugin=hot.getPlugin('exportFile');
Handsontable.dom.addEvent(searchFiled, 'keyup', function(event) {
var queryResult;
console.log(this.value);
searchResultCount = 0;
queryResult = hot.search.query(this.value);
console.log(queryResult);
//resultCount.innerText = searchResultCount.toString();
hot.render();
});
buttons.file.addEventListener('click', function() {// enabling the plugin to download the file
exportPlugin.downloadFile('csv', {filename: 'MyFile',columnHeaders:true});
});
I don't get any error when i remove the if/else statement and use only one scenerio .when using above code i am getting the error, but when i remove the if/else part and just use columns attribute in a simple way , i don't get this error.But i want to have different views for the creator of plan and others.
Is there any other way to do this?
Thanks

You can't use if statements when constructing an object, but you can use the ternary ?: operator, like this:
colHeaders: ... ,
columns: logged_user == plan_creator
? /* value in case they are equal */
: /* value in case they are not equal */,
search: ...

instead of using if else like
if(logged_user == plan_creator) {
columns:[//when using this not able to remove column
{data:'tc_name'},
{data:'cell_name'},
{data:'customer_name'},
{data:'flops' ,type:'numeric'},
{data:'title'},
{data:'status'},
{data:'mfix_ccr'},
{data:'test_scenerio'},
{data:'expected_results'},
{data:'ccr_status'},
{data:'ccr_num'},
{data:'remarks'},
{data:'tc_path'}],
}
else {}
you could use the ternary Operator:
columns: (logged_user === plan_creator)
? [//when using this not able to remove column
{data:'tc_name'},
...
]
: [//when using this not able to remove column
{data:'tc_name' ,readOnly:true },
...
]

Related

Access specific line Datatable

I am defining a Datatable this way:
var dat_one = $('#dat_one').DataTable({
select: {
style: 'single'
},
responsive: true,
});
I would like to access a specific line of my datatable. I want to color a line that contains a specific string. (Example: Line that contains 'Ashton Cox' as column 1 and 'San Francisco' as column 3
I tried to color a selected line with this code :
$(".selected").css('background-color', '#ccffcc');
But doesn't works if my line is not selected.
Try using rowCallback. There you can change row attributes with value checking.
$('#example').dataTable( {
"rowCallback": function( row, data ) {
if ( data.grade == "A" ) {
$('td:eq(4)', row).html( '<b>A</b>' );
}
}
} );
This is documentation. Note the function has many other parameters you can use.
rowCallback( row, data, displayNum, displayIndex, dataIndex )
Following documentation, this is an alternative to Aruna Perera:
// var table = $('#dat_one').DataTable() ;
dat_one.rows().eq(0).each( function ( index ) {
var row = table.row( index );
var data = row.data();
var column0value = data[0];
if(column0value == "Airi Satou"){
$(row.node()).css("background-color", "yellow")
}
// ... do something with data(), or row.node(), etc
} );

Javascript - adding comma automatically to input field

I will post the part of a function that is adding numbers that are clicked into selected input field.
So, I need to separate it with a comma (,). I tried some of the examples but it seems not to be working on the function that I wrote.
var rowRange = 'abcdefghijklmnopqrstuvwxyz'.split('');
var $cart = $('#seats'),
$counter = $('#counter'),
sc = $('#seat-map').seatCharts({
map: [
'aaaaa__aaaaa',
'aaaaa__aaaaa'
],
naming : {
top : false,
getLabel : function (character, row, column) {
return rowRange[row - 1].toUpperCase() + column;
},
},
click: function () {
if (this.status() === 'available') {
$('#seats').split(",")
.attr('id', 'cart-item-'+this.settings.id)
.val(this.settings.label)
.appendTo($cart);
$counter.text(sc.find('selected').length+1);
return 'selected';
});
});
Seat is a input field where comma needs to be added after every click on any number.
.split(",")
when I remove this part the code works like it should, but without adding comma.
.split() doesn't work on jquery objects. Instead use it on the values in your select.
Here is an example on how it could work.
$selected = $('#selected');
$(".seat").on("click", function() {
const cur = $selected.val();
const valToInsert = $(this).text();
$selected.val(cur.length === 0 ? valToInsert : cur.split(',').concat(valToInsert).join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="selected">
<button class="seat">a</button>

jexcel table SUM column after change

I want to sum a column in jexcel after entering a value
This code is not working I don't know why:
var change = function(instance, cell, value) {
var cellName = $(instance).jexcel('getColumnNameFromId',$(cell).prop('id'));
$('#log').append('New change on cell'+ cellName+'to:'+ value + '<br>');
var thisid = $(cell).prop('id');
var splitted = thisid.split("-");
var nextcellid = ++splitted[1];
var nextcell = '0-'+nextcellid;
console.log(nextcell,'nextcell');
$("td#"+nextcell).html('<span>total</span>');
}
using onafterchange event:
$('#my').jexcel({
data:data,
colHeaders: ['Model'],
colWidths: [ 300 ],
onafterchange:function(instance){
console.log(instance)
},
columns: [
{ type: 'text' },
]
});
full handing events ready this url
https://bossanova.uk/jexcel/docs/events
or using this example
https://bossanova.uk/jexcel/examples/including-formulas-on-your-spreadsheet
To be honest, you can just use =SUM(A1:A10) in the column you would like to have the total. Pretty much like excel.

Datatables: Export Excel Formatting

I'm having some issues when trying to format data when exporting to Excel using datatables. One of my columns contain a decimal point and displays OK when viewed in the browser as a table. When I export the table to excel this is rounding up the number in that column, this I do not want to happen. e.g shown in table '220419.07109' and when exported '220419.0711' I would prefer if this was just a string to maintain the full number.
function formatDataForExport(data, row, column, node) {
var string = data.toString();
return string;
}
function drawDatatable(JSONData) {
var dataSet = [];
table = $("#div").DataTable({
data: dataSet,
columns: columns(),
columnDefs: [{
"targets": columnTargets(showConcludedColumns),
"visible": false,
"searchable": false
}],
info: false,
searching: false,
paging: false,
ordering: false,
autoWidth: true,
responsive: true,
buttons: [{
extend: 'excel',
text: "Export to Excel",
exportOptions: {
columns: ":visible",
format: {
body: formatDataForExport
}
}
}]
});
}
You could use the following solution.
// Get the max value of an attribute of elements' list
var getMaxValue = function(elements, attr) {
var values = elements.map(function(){
return this.getAttribute(attr) || -Infinity;
}).toArray();
return Math.max.apply(Math, values);
}
$('#example').DataTable( {
dom: 'Bfrtip',
columns: [
{ data: 'Number' },
],
buttons: [
{
extend: 'excelHtml5',
customize: function(xlsx) {
//Get the built-in styles
//refer buttons.html5.js "xl/styles.xml" for the XML structure
var styles = xlsx.xl['styles.xml'];
//Create a custom number format
//Get the available id for the custom number format
var numFmtId = getMaxValue($('numFmts numFmt', styles), 'numFmtId') + 1
//XML Node: Custom number format for the timestamp column
var nFmt = '<numFmt numFmtId="' + numFmtId + '" formatCode="0.######################"/>';
// Add new node
el = $('numFmts', styles);
el.append(nFmt).attr('count', parseInt(el.attr('count'))+1);
//Create our own style to use the custom number format above
//XML Node: Custom style for the timestamp column
var style = '<xf numFmtId="' + numFmtId + '" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/>';
// Add new node
el = $('cellXfs', styles);
el.append(style).attr('count', parseInt(el.attr('count'))+1);
// Index of our new style
var styleIdx = $('xf', el).length - 1;
//Apply new style to the first (A) column
var sheet = xlsx.xl.worksheets['sheet1.xml'];
//Set new style default for the column (optional)
$('col:eq(0)', sheet).attr('style', styleIdx);
//Apply new style to the existing rows of the first column ('A'), skipping header row
$('row:gt(0) c[r^="A"]', sheet).attr('s', styleIdx);
},
},
]
} );
Working JSFiddle
You could use different kinds of formatting there:
0.###################### - will show as many digits after decimal point as you have "#";
#.###################### - the same as above, but with no 0 in a number like 0.1234;
0.?????????????????????? - the same as above, but aligned by the decimal point
Simplified version, the resulted file opens correctly in Excel, but the shortcuts could affect other XLSX files reading software: JSFiddle

Filtering an exact of string in DataTable JQuery

How do I search for an exact match in the search bar of JQuery Datable I tried using fnFilter but it's still not returning an exact match.
$(document).ready(function() {
var oTable = $('#datacal_table').DataTable({"order": [[4, "asc"]]});
oTable.fnFilter("^"+$(this).val()+"$", 4, true);
});
For example I only watch to search 'active' but what happens is the 'inactive' words also returns in the result. What should I do I need to be able to search only the the exact string.
EDIT
I tried one of inuka's links How to search for an exact string in a jQuery DataTable?
and it seems like my text class is interfering with the search, how do I get around this? I want to keep using my class text so that it's colored.
<td id="status">
<span class = "label {{ getStatusColor($data->status) }}"
id = "status_{{ $data->id }}">
{{ getStatusText($data->status) }}
</span>
</td>
when I only retain {{getStatusText}} the search works but when I try to class it, it doesn't.
<script type="text/javascript">
$(document).ready(function() {
var table = $('#datacal_table').DataTable({
"order": [[4, "asc"]]
});
$('.dataTables_filter input', table.table().container())
.off('.DT')
.on('keyup.DT cut.DT paste.DT input.DT search.DT', function(e) {
var term = $.trim(this.value);
if (term !== ""){
var termRegExp = new RegExp('^' + $.fn.dataTable.util.escapeRegex(term) + '$', 'i');
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex){
var isFound = false;
$.each(data, function (index, value) {
if (termRegExp.test(value)){ isFound = true; }
return !isFound;
});
return isFound;
}
);
}
table.draw();
if (term !== "") {
$.fn.dataTable.ext.search.pop();
}
});
});
</script>
The following answer from this post will give you an answer for searching term inside your HTML table structure.
$('#datacal_table').DataTable({
"columnDefs": [{
"targets": [4],
"render": function ( data, type, full, meta ) {
if(type === 'filter'){
return $('#datacal_table').DataTable().cell(meta.row, meta.col).nodes().to$().find('span').text();
} else {
return data;
}
}
}]
});
According to Datatables documentation this columnDefs.targets will give you the option to match only specified column name values. "targets": [4] will only focus on values under your Status column.
try this code
var oTable = $('.datatable').DataTable();
$('.dataTables_filter input').keyup( function () {
oTable.fnFilter("^"+$(this).val(),0,true,false);
});
working link http://codepen.io/subbu1191/pen/GmrvNd
1.{string}: String to filter the table on
2.{int|null}: Column to limit filtering to
3.{bool} [default=false]: Treat as regular expression or not
4.{bool} [default=true]: Perform smart filtering or not
5.{bool} [default=true]: Show the input global filter in it's input box(es)
6.{bool} [default=true]: Do case-insensitive matching (true) or not (false)
you have to make the smart filtering false in order to get the regex working

Categories

Resources