Export to csv using java script - javascript

I am facing problem with exporting csv.
Problems:
1) I have to export a html table to csv file . Can i change the delimiter of csv file to something else like semicolon. If I have values in the table under the same column separated by comma, in the csv sheet it is showing in a different column.
2) My code is not working for IE and it is only working for mozilla
3) Also I wanted the user to save the csv file. Now it is getting automatically saved.
Please find my code . Can any body help with any of the issue.
function exportTableToCSV(filename) {
var tab = $('#searchObjectTableTabs').tabs('getSelected');// selecting the table
var tabIndex = $('#searchObjectTableTabs').tabs('getTabIndex', tab);
var data;
var rows;
if (tabIndex == '0') // first index of the tab under which the table will be displayed
{
data = $('#dg');//Only one table
rows = $('#dg').datagrid('getRows');
} else if (tabIndex == '1') // second index
{
data = $('#doc').first(); //Only one table
rows = $('#doc').datagrid('getRows');
}
var csvData = [];
var tmpArr = [];
var tmpStr = '';
data.find("tr").each(function ()
{
if ($(this).find("th").length) {
$(this).find("th").each(function () {
tmpStr = $(this).text().replace(/"/g, '""');
tmpArr.push('"' + tmpStr + '"');
});
csvData.push(tmpArr);
}
tmpArr = [];
$.each(exportArray, function (index, value)
{
csvData.push(exportArray[index].type + "," + exportArray[index].status + "," + exportArray[index].ID + "," + exportArray[index].itemrev + "," + exportArray[index].desc + "," + exportArray[index].owner + "," + exportArray[index].ogrp);
});
csvData.push(tmpArr.join('\n'));
// printObject(tmpArr);
});
alert('before this');
var output = csvData.join('\n');
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(output);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
'delimiter':';'
});
alert('done');
}
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this,['export.csv']);
});

Related

Definig element.sortable()-function

My html table supports changing the row-order using mouse drag and drop. The used jquery-ui version is v1.12.1. It works for old tables (i.e. those whose row count is known since load of the page), but it doesn't work for rows added after the page has been loaded. I think the reason is that the below sortable()-function is inside document.ready()-function.
<script type="text/javascript">
<script src="{% static 'js/jquery-ui.js' %}"></script>
$(document).ready(function(){
$('#luok_table tbody').sortable({
stop: function( event, ui ){
$(this).find('tr').each(function(i){
$(this).attr("id", $(this).attr("id").replace(/\d+/, i) );
$(this).find(':input').each(function(){
$(this).attr("id", $(this).attr("id").replace(/\d+/, i) );
$(this).attr("name", $(this).attr("name").replace(/\d+/, i) );
});
});
}
});
});
</script>
If that's the reason, where should I define the sortable()-function ?
The table rows are added by jquery-formset-js-script:
;(function($) {
$.fn.formset = function(opts)
{
var options = $.extend({}, $.fn.formset.defaults, opts),
flatExtraClasses = options.extraClasses.join(' '),
$$ = $(this),
applyExtraClasses = function(row, ndx) {
if (options.extraClasses) {
row.removeClass(flatExtraClasses);
row.addClass(options.extraClasses[ndx % options.extraClasses.length]);
}
},
updateElementIndex = function(elem, prefix, ndx) {
var idRegex = new RegExp('(' + prefix + '-\\d+-)|(^)'),
replacement = prefix + '-' + ndx + '-';
if (elem.attr("for")) elem.attr("for", elem.attr("for").replace(idRegex, replacement));
if (elem.attr('id')) elem.attr('id', elem.attr('id').replace(idRegex, replacement));
if (elem.attr('name')) elem.attr('name', elem.attr('name').replace(idRegex, replacement));
},
hasChildElements = function(row) {
return row.find('input,select,textarea,label').length > 0;
},
insertDeleteLink = function(row) {
if (row.is('TR')) {
// If the forms are laid out in table rows, insert
// the remove button into the last table cell:
row.children(':last').append('<a class="' + options.deleteCssClass +'" href="javascript:void(0)">' + options.deleteText + '</a>');
} else if (row.is('UL') || row.is('OL')) {
// If they're laid out as an ordered/unordered list,
// insert an <li> after the last list item:
row.append('<li><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText +'</a></li>');
} else {
// Otherwise, just insert the remove button as the
// last child element of the form's container:
row.append('<a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText +'</a>');
}
row.find('a.' + options.deleteCssClass).click(function() {
var row = $(this).parents('.' + options.formCssClass),
del = row.find('input:hidden[id $= "-DELETE"]');
if (del.length) {
// We're dealing with an inline formset; rather than remove
// this form from the DOM, we'll mark it as deleted and hide
// it, then let Django handle the deleting:
del.val('on');
row.hide();
} else {
row.remove();
// Update the TOTAL_FORMS form count.
// Also update names and IDs for all remaining form controls so they remain in sequence:
var forms = $('.' + options.formCssClass).not('.formset-custom-template');
$('#id_' + options.prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
applyExtraClasses(forms.eq(i), i);
forms.eq(i).find('input,select,textarea,label').each(function() {
updateElementIndex($(this), options.prefix, i);
});
}
}
// If a post-delete callback was provided, call it with the deleted form:
if (options.removed) options.removed(row);
return false;
});
};
$$.each(function(i) {
var row = $(this),
del = row.find('input:checkbox[id $= "-DELETE"]');
if (del.length) {
// If you specify "can_delete = True" when creating an inline formset,
// Django adds a checkbox to each form in the formset.
// Replace the default checkbox with a hidden field:
del.before('<input type="hidden" name="' + del.attr('name') +'" id="' + del.attr('id') +'" />');
del.remove();
}
if (hasChildElements(row)) {
insertDeleteLink(row);
row.addClass(options.formCssClass);
applyExtraClasses(row, i);
}
});
if ($$.length) {
var addButton, template;
if (options.formTemplate) {
// If a form template was specified, we'll clone it to generate new form instances:
template = (options.formTemplate instanceof $) ? options.formTemplate : $(options.formTemplate);
template.removeAttr('id').addClass(options.formCssClass).addClass('formset-custom-template');
template.find('input,select,textarea,label').each(function() {
updateElementIndex($(this), options.prefix, 2012);
});
insertDeleteLink(template);
} else {
// Otherwise, use the last form in the formset; this works much better if you've got
// extra (>= 1) forms (thnaks to justhamade for pointing this out):
template = $('.' + options.formCssClass + ':last').clone(true).removeAttr('id');
template.find('input:hidden[id $= "-DELETE"]').remove();
template.find('input,select,textarea,label').each(function() {
var elem = $(this);
// If this is a checkbox or radiobutton, uncheck it.
// This fixes Issue 1, reported by Wilson.Andrew.J:
if (elem.is('input:checkbox') || elem.is('input:radio')) {
elem.attr('checked', false);
} else {
elem.val('');
}
});
}
// FIXME: Perhaps using $.data would be a better idea?
options.formTemplate = template;
if ($$.attr('tagName') == 'TR') {
// If forms are laid out as table rows, insert the
// "add" button in a new table row:
var numCols = $$.eq(0).children().length;
$$.parent().append('<tr><td colspan="' + numCols + '"><a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a></tr>');
addButton = $$.parent().find('tr:last a');
addButton.parents('tr').addClass(options.formCssClass + '-add');
} else {
// Otherwise, insert it immediately after the last form:
$$.filter(':last').after('<a class="' + options.addCssClass + '" href="javascript:void(0)">' + options.addText + '</a>');
addButton = $$.filter(':last').next();
}
addButton.click(function() {
var formCount = parseInt($('#id_' + options.prefix + '-TOTAL_FORMS').val()),
row = options.formTemplate.clone(true).removeClass('formset-custom-template'),
buttonRow = $(this).parents('tr.' + options.formCssClass + '-add').get(0) || this;
applyExtraClasses(row, formCount);
row.insertBefore($(buttonRow)).show();
row.find('input,select,textarea,label').each(function() {
updateElementIndex($(this), options.prefix, formCount);
});
$('#id_' + options.prefix + '-TOTAL_FORMS').val(formCount + 1);
// If a post-add callback was supplied, call it with the added form:
if (options.added) options.added(row);
return false;
});
}
return $$;
}
/* Setup plugin defaults */
$.fn.formset.defaults = {
prefix: 'form', // The form prefix for your django formset
formTemplate: null, // The jQuery selection cloned to generate new form instances
addText: 'add another', // Text for the add link
deleteText: 'remove', // Text for the delete link
addCssClass: 'add-row', // CSS class applied to the add link
deleteCssClass: 'delete-row', // CSS class applied to the delete link
formCssClass: 'dynamic-form', // CSS class applied to each form in a formset
extraClasses: [], // Additional CSS classes, which will be applied to each form in turn
added: null, // Function called each time a new form is added
removed: null // Function called each time a form is deleted
};
})(jQuery)

How to render multiple html lists with AppScrip?

I am new to the world of * AppScript * I am currently designing a ** WepApp ** which is made up of html lists that connect to Mysql, when I individually test my lists paint correctly and their icons modify and update the data, without However ** the problem is ** when I join all my lists and call them through their corresponding url only the last one paints me the others are blank. For example of 10 lists I call # 2 the log tells me to call 10; I call 5 the same thing happens and if I call 10 it paints the data and they are allowed to be modified.
Within what I have searched I find that my problem lies in the way I render my pages but I cannot find the right path, so I ask for your support.
function doGet(e) {
var template ;
var view = e.parameters.v;
if(view == null){
template = HtmlService.createTemplateFromFile("Index");
}if(view == "Index"){
template = HtmlService.createTemplateFromFile("Index");
}if(view != null && view != "Index"){
template = HtmlService.createTemplateFromFile(view);
}
return template.evaluate()
.setTitle('Documental')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getTemplate(view){
return HtmlService.createTemplateFromFile(view);
}
and with this JavaScript method I connect my appscript code to pass it to my html
window.onload = function () {
google.script.run
.withSuccessHandler(run_This_On_Success)
.withFailureHandler(onFailure)
.readAreaPRE();
};
function onFailure(error) {
var div = document.getElementById("output");
div.innerHTML = "ERROR: " + error.message;
}
function run_This_On_Success (readAreaPRE) {
let table = $("#selectTable");
table.find("tbody tr").remove();
table.append("<tr><td>" + "</td><td>" + "</td></tr>");
readAreaPRE.forEach(function (e1, readAreaPRE) {
table.append(
"<tr><td>" +
e1[0] +
"</td><td>" +
e1[1] +
"</td><td>" +
"<p><a class='modal-trigger' id=" + e1[0] + " href='#modal1' onclick='capturaid("+e1[0]+",'"+ e1[1]+"')'><i class='material-icons'>edit</i></a>" +
"<a class='modal-trigger' href='#modal3' onclick='capturaidsup("+e1[0]+")'><i class='material-icons'>delete</i></a></p>" +
"</td></tr>"
);
});
};
function capturaidsup(dato1){
$("#delAreaPRE").val(dato1)
}
function capturaid(item1,item2) {
$("#uptAreaPRE1").val(item1);
$("#uptAreaPRE2").val(item2);
}
here is my function: readArePRE
function readAreaPRE() {
var conn = Jdbc.getCloudSqlConnection(url, user, contra);
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery(
"CALL `BD_CENDOC_COL`.`sp_lee_tb_ref_AreasPRE`()"
);
var numCols = results.getMetaData().getColumnCount();
var rowString = new Array(results.length);
var i = 0;
while (results.next()) {
var id_areaPRE = results.getInt("id_areaPRE");
var AreaPRE = results.getString("AreaPRE");
rowString[i] = new Array(numCols);
rowString[i][0] = id_areaPRE;
rowString[i][1] = AreaPRE;
i++;
}
return rowString;
conn.close();
results.close();
}
Thank you in advance, any correction to ask my question will be welcome.

Verify if data already in db, with more inputs same class

I have (part of) a form HTML produced by a PHP loop:
<input type="text" class="store">
<input type="text" class="store">
<input type="text" class="store">
<input type="text" class="store">
The input goes in a db tables:
store
-------
cityID
cityname
store
I have a JavaScript that alerts me if the store entered is already in other cities:
$(document).ready(function() {
$('.store').on('change', function() {
var storeValue = $('.store').val();
$.post('stores.php', {'word': storeValue}, function(data) {
var verifStore = '';
var json = $.parseJSON(data);
$.each(json, function(k, v) {
verifStore += '[' + v.cityID + '] ' + v.cityName + '\n';
});
alert('Already in the following cities: ' + '\n' + verifStore);
});
});
});
Problem is that JavaScript is fired by the .class and I have more .class inputs in my form, so (of course) it doesn't work properly. How should I modify my JavaScript code? Maybe there is in JavaScript a way to consider each .class field separately... Something like .each or .foreach ...?
Let's say, you have been asked to put 4 different values for the city and they are not supposed to be present in the DB. I would create a class named error:
.error {border: 1px solid #f00; background: #f99;}
And now, I would go through each of the input using $.each:
$(".store").each(function () {
$this = $(this);
$this.removeClass("error");
$.post('stores.php', {'word': $this.val()}, function (data) {
if ( /* Your condition if the word is present. */ )
alert("Already there!");
});
});
Note that this code will send as many as requests to the server as many inputs are there. So handle with care.
You can optimize your function if you do just one request.
var values = $(".store").map(function(){
return this.value;
}); // values is an array
$this.removeClass("error");
// stores.php should be ready to receive an array of values
$.post('stores.php', {'word': JSON.stringify(values)}, function (data) {
var verifStore = '';
var json = $.parseJSON(data);
$.each(json, function(k, v){
verifStore += '[' + v.cityID + '] ' + v.cityName + '\n';
});
if(varifStore)
alert('Already in the following cities: ' + '\n' + verifStore);
});
SOLUTION (at least for me...)
After reading all answers and suggestions, I was able to make it work with this code. Hope it will be helpful for others :)
$(document).ready(function() {
$('.store').each (function(){//do it for every class .store
var $this = $(this); //get this object
$this.on('change', function(){ //when this change...
var searchValue = this.value; //assign the input to a variable
if (searchValue != ''){ //if the variable is not emprty
$.post('stores.php',{'term' : searchValue}, function(data) { //check and return data in alert
if (data.length < 10){ // if number not in db, green
$this.css({'border' : 'solid 4px #17BC17'});
}
var resultAlert = '';
var jsonData = $.parseJSON(data);
$.each(jsonData, function(k, v){
resultAlert += '[' + v.cityID + '] ' + v.cityname + ' ' + v.value + '\n';
}); //each
alert('ALERT!' + '\n' + 'store in other cities' + '\n' + searchValue + ': ' + '\n' + resultAlert );
$this.css({'border' : 'solid 4px #FFCC11'}); // if in db, yellow
});// post
}//close if
if (searchValue == ''){ //if the variable is empty, this turn green, if you delete a yellow number
$this.css({'border' : ''});
}
}); //close on change
});//close .each
});

Modifying innerHTML in nested get() jQuery

I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?

accessing a specific column in a csv file using javascript

My problem is simple. I would like to know if there is a way to access a specific column from a csv file which is in MS Excel format. There are about 40 fields or columns in the file. I want to access only 3 of these. Please guide me.
Thanks in advance
This is as far as I got. Can we count the number of columns in the file?
$(document).on("click","#bucket_list a",function(evt){
// console.log("ID :: ",evt.target.id);
var bucketID = evt.target.id;
evt.preventDefault();
// alert("Event Fired");
counter = 0;
//lists the bucket objects
s3Client.listObjects(params = {Bucket: bucketID}, function(err, data){
if (err) {
document.getElementById('status').innerHTML = 'Could not load objects from ' + bucketID;
} else {
//document.getElementById('status').innerHTML = 'Loaded ' + data.Contents.length + ' items from ' + bucketID;
var listStart = document.createElement("ul");
document.getElementById('status').appendChild(listStart);
for(var i=0; i<data.Contents.length;i++){
fileKey = data.Contents[i].Key;
if(fileKey.search(str) != -1) {
//var listItems = document.createElement("li");
//listItems.innerHTML = data.Contents[i].Key;
//listStart.appendChild(listItems);
fileList[i] = data.Contents[i].Key;
//alert(fileList[i]);
counter = counter + 1;
}
}
if(counter == 0){
alert("This bucket has no CSV files. Please try another bucket!");
}
// else{
// for(var i = 0; i<fileList.length;i++){
// alert("File: " + fileList[i]);
// }
// }
}
//to read the contents of the files into textviews
var file = fileList[0];
//console.log("Loading:: ", file);
s3Client.getObject(params={Bucket: bucketID, Key: file},function(err,data){
if(err != null){ alert("Failed to load object " + err); }
else{
//alert("Loaded " + data.ContentLength + " bytes");
var allDataLines = data.split(/\r\n|\n/);
var headers = allDataLines[0].split(',');
}
});
});
});
I am unable to figure out how to get only the second column.
Yes. You have to parse the csv file to get the values for a particular column.Refer the following post on how to read a CSV file in Javascript.
[How to read data From *.CSV file using javascript?
To give you a head start the logic is simple . You just have to split based on "," and do a if statement.

Categories

Resources