Parse ASCII as plain text exporting to Excel from js - javascript

Having a bit of trouble when exporting a spreadsheet. The tool is to create tracking links, everything works fine except when the link contains ascii characters. For example, someurl.com&trackingparameter%3d.
When this happens, it all works within the app, but when exported to the spreadsheet it would read as someurl.com&trackingparameter=.
Wondering how I can parse these ascii characters as plain text on the export. Thanks in advance for any assistance.
Best,
Erik
<script>
$(document).ready(function() {
$("#btnExport").click(function(e) {
e.preventDefault();
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('wrapper');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
var a = document.createElement('a');
a.href = data_type + ', ' + table_html;
a.download = 'exported_URLS_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
a.click();
});
});
</script>
<script type="text/javascript">
function createTable() {
var deletebutton = '<button class="delete uk-button uk-button-danger" id="delete">delete</button>';
var tbody = '';
var descripdata = '';
var simpleURLdata = '';
var description = document.getElementById('description').value;
var simpleURL = document.getElementById('simpleURL').value;
var baseURL = document.getElementById('baseURL').value;
var s1 = document.getElementById('s1').value;
var s2 = document.getElementById('s2').value;
var s3 = document.getElementById('s3').value;
var s4 = document.getElementById('s4').value;
var ts = document.getElementById('ts').value;
var hdr = document.getElementById('hdr').value;
var hdrid = document.getElementById('hdrid').value;
var dmhdr = document.getElementById('dmhdr').value;
var utm_source = document.getElementById('utm_source').value;
var utm_medium = document.getElementById('utm_medium').value;
var utm_campaign = document.getElementById('utm_campaign').value;
var utm_category = document.getElementById('utm_category').value;
tbody += '<td>';
tbody += baseURL;
if (s1 != '') {
tbody += '&s1=';
tbody += s1;
}
if (s2 != '') {
tbody += '&s2=';
tbody += s2;
}
if (s3 != '') {
tbody += '&s3=';
tbody += s3;
}
if (s4 != '') {
tbody += '&s4=';
tbody += s4;
}
if (ts != '') {
tbody += '&ts=';
tbody += ts;
}
if (hdr != '') {
tbody += '&hdr='
tbody += hdr;
}
if (dmhdr != '') {
tbody += '&dmhdr=';
tbody += dmhdr;
}
if (hdrid != '') {
tbody += '&hdrid=';
tbody += hdrid;
}
if (utm_source != '') {
tbody += '&utm_source=';
tbody += utm_source;
}
if (utm_medium != '') {
tbody += '&utm_medium=';
tbody += utm_medium;
}
if (utm_campaign != '') {
tbody += '&utm_campaign=';
tbody += utm_campaign;
}
if (utm_category != '') {
tbody += '&utm_category=';
tbody += utm_category;
}
tbody += '</td>';
descripdata += '<td>';
if (description != '') {
descripdata += description;
}
descripdata += '</td>';
simpleURLdata += '<td>';
if (simpleURL != '') {
simpleURLdata += simpleURL;
}
simpleURLdata += '</td>';
var table = document.getElementById('urls');
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = tbody;
var cell2 = row.insertCell(1);
cell2.innerHTML = descripdata;
var cell3 = row.insertCell(2);
cell3.innerHTML = simpleURLdata;
var cell4 = row.insertCell(3);
cell4.innerHTML = deletebutton;
}
</script>

You can use javascript native functions escape(), encodeURI() or encodeURIComponent() if you want to retain %3d as %3d.
Further help regarding these can be found at When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Related

Dynamically generated table with checkbox overflowing the parent div element

I am trying to create a table dynamically using javascript. I want each table to have a checkbox beside it. So, I have written the following code:
JAVASCRIPT
label_submit_btn.addEventListener("click", function(event){
event.preventDefault();
var formInputs = document.getElementById("label_query_form").querySelectorAll("input");
validation = validateForm(formInputs);
if(validation[0]){
var label_query_form_action = document.getElementById("label_query_form").getAttribute("action");
var label_val = document.getElementById("label_no")
query_db("label_data_div", label_query_form_action, label_val, true, "label_query_row");
// var chk_boxes = document.getElementsByClassName("form-check-input");
// document.getElementById("data_delete_btn").disabled = false;
}
else{
alert(validation[1])
}
});
function query_db(output_div, form_action, form_data, add_checkbox, row_class){
document.getElementById(output_div).innerHTML = ""
var xhr = new XMLHttpRequest();
var formData = new FormData();
formData.append(form_data.name, form_data.value)
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
let response_data = JSON.parse(this.responseText);
let table_data = JSON.parse(response_data);
table_data = create_table_from_json(table_data, add_checkbox, row_class);
document.getElementById(output_div).innerHTML += table_data;
}
}
xhr.open("POST", form_action, true);
xhr.send(formData);
}
function create_table_from_json(table_data, add_checkbox, row_class){
var table_rows = "";
for (var i = 0; i < table_data["columns"].length; i++) {
table_rows += "<th>" + table_data["columns"][i] + "</th>";
}
table_rows += "<th>Select</th>";
console.log(table_rows);
table_rows = "<tr>" + table_rows +"</tr>";
for (var i = 0; i < table_data["data"].length; i++) {
trow = ""
for (var j = 0; j < table_data["columns"].length; j++) {
trow += "<td class="+ table_data["columns"][j] +">" + table_data["data"][i][j] + "</td>";
}
if(add_checkbox == true){
trow += '<td><input type="checkbox" class="form-check-input"/> </td>';
}
table_rows += "<tr class="+ row_class + ">" + trow +"</tr>";
}
return "<table><tbody>" + table_rows + "</table></tbody>";
}
HTML
<div class="container" id="label_data_div" style="height: 200px;overflow: scroll;"></div>
Now, while rendering the page, all of the checkboxes are overflowing outside of the div element(see image).

JavaScript does not work in IE 11 with Error-DOM7011

This code is to upload a csv file and change to a table form. It works on chrome and safari, but it doesn't on IE... I have no idea what I should change. I was wondering how to fix it.
DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337.
var numQ = 0;
function openCsvFile(){
var input = document.createElement("input");
input.type = "file";
input.accept="text/plain, text/html, .jsp, .csv";
input.click();
input.onchange = function(event){
processFile_csv(event.target.files[0]);
};
}
function processFile_csv(file){
var pass_head = 0;
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function(){
var allRows = reader.result.split(/\r?\n|\r/);
var table = '<!DOCTYPE html><html lang="ko"><head><meta charset="UTF-8"><meta http-equiv pragma content no-cache ><meta http-equiv="X-UA-Compatible" content="IE=Edge; chrome=1" /><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"><meta http-equiv="Pragma" content="no-cache"><meta http-equiv="Expires" content="0"></head><table id="output" border="1">';
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
if (singleRow === 0) {
table += '<thead>';
table += '<tr align ="center">';
} else {
table += '<tr align = "center">';
}
var rowCells = allRows[singleRow].split(',');
for (var rowCell = 0; rowCell < rowCells.length; rowCell++) {
if (singleRow === 0) {
table += '<th align = "center">';
table += rowCells[rowCell];
table += '</th>';
} else {
if (rowCells[0] != "") {
table += '<td align = "center">';
if(rowCell == 0){
table += "a";
}
table += rowCells[rowCell];
table += '</td>';
}
}
}
if (singleRow === 0) {
table += '</tr>';
table += '</thead>';
table += '<tbody>';
} else {
table += '</tr>';
}
}
document.getElementById("output").innerHTML = table;
};
}

Close and create a <tr> tag after every four <td> elements. Is it a loop?

I retrieved my list of users from my db and now I want to add them to my page. I am trying to display the users using a table and make sure that they appear four per row and then jump to the new row, but I am not certain how to do this. Here is my js file so far. Please let me know if there is anything else you need.
var space = new Array("username", "user_id","address","state","postal_code","phone","email");
$(document).ready( function() {
var obj = '';
$.getJSON( "obtainUsers.php", function(data) {
var num = 1;
var json = JSON.stringify(data);
obj = jQuery.parseJSON(json);
var html = "";
var tot_obj = obj.length ;
var upper = (num*10)-1;
var lower = (num*10)-10;
var max = ( upper < tot_obj ) ? upper : tot_obj ;
html += "<div><table width:'100%'><tr>";
for (var i = lower; i <= max-1 ; i++ )
{
var toggle = i % 2;
var list_items = "";
columns.forEach( function(col)
{
if ( obj[i][col] != null ) {
if ( obj[i][col] !== "" )
{
if ( obj[i].level == 'NEW' ) {
list_items += "<div class='new_client'>";
list_items += obj[i][col] + "</div >";
}
else if( obj[i].level == 'RENEWAL' ) {
list_items += "<div class='renewing_client'>";
list_items += obj[i][col] + "</div >";
}
else if( obj[i].level == 'CURRENT' ) {
list_items += "<div class='current_client';>";
list_items += obj[i][col] + "</div >";
//console.log(obj[i][col]);
}
}
}
} );
list_items += "</br >";
if ( toggle == 0 )
{
html += "<td><div class='table_styles'> ";
html += list_items ;
//console.log(list_items);
html += "</div></td>";
console.log(html);
}
else
{
html += "<td><div class='table_styles'> ";
html += list_items;
html += "</div></td>";
}
}
html += "</tr> </table></div>";
$('.runninglist').html(html);
});
});
var columns = ["username","user_id","address","state","postal_code","phone","email"];
var level_classes = {"NEW":"new_client", "RENEWAL":"renewing_client", "CURRENT":"current_client"};
$(document).ready( function() {
$.getJSON("obtainUsers.php", function(data) {
var $table = $('<table style="width: 100%;">');
var $tbody = $('<tbody>');
$table.append($tbody);
var $tr = null;
data.forEach(function(user, index){
if(index % 4 === 0) {
$tr = $('<tr>');
$tbody.append($tr);
}
$td = $('<td class="'+level_classes[user.level]+'">');
columns.forEach(function(col){
$td.append(user[col]);
$td.append($('<br>'));
});
$tr.append($td);
});
$('.runninglist').append($table);
});
});

Dynamically creating an html table with Javascript

I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got this working in PHP, however i would like the user to be able to see the table before the query it. I found a script on here that partially did what I wanted and have attempted to edit it (I found it surprisingly similar to PHP) Basically it calculates the total amount of cells (ports) splits it by rows and columns, the "super" column is used if the user would like it to be split into multiple tables, which align next to each other, hence the div tag. Here's my JS:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for(u=1; u<=num_row; u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
Here is what the final output looks like after it has been processed by PHP (ports:24, col:6, rows:2, super:2):
Here is a js fiddle that I threw together:
http://jsfiddle.net/9SnLB/
Currently, when I click the button nothing happens, but, I suppose that is my first issue, but am I going about the setup correctly? Why wont the button run the function?
Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for($u=1; $u<=num_rows; $u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
document.write("<tr>");
for(y = table[x].length;y > 0;y--) {
document.write("<td>"+y+"</td>");
}
document.write("</tr>");
}
Sorry if the syntax is wrong. You get the idea.
You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".
here's the corrected js.
function createTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
var theader = '<div><table border="1">\n';
for ($u = 1; $u <= num_rows; $u++) {
tbody += '<tr>';
for (var j = 0; j < colStart; j++) {
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}

How to add header for dynamic table

Hello everybody I am drawing dynamic table and I want to add header for table how to add header to dynamic table here is my table code:
$.get('http://myDomain.com/RIA/topIndiaDetails.asp', function(data)
{
console.log("####"+data);
var up = new Image();
var down = new Image();
up.src = "../../jquery.mobile/images/up.png";
down.src = "../../jquery.mobile/images/down.png"
substr = data.split('$');
//alert(substr.length);
//var theader = '<table border="1">\n';
//<table id="auditOverview" border="1">
var theader = '<table border="1" id=\"tableId\">\n';
var tbody = '';
for (var out = 1;out<substr.length-1;out++)
{
//alert(substr[out]);
tbody += '<tr>';
var pra = substr[out].split('|^');
//alert('pra.length is: '+pra.length);
for (var i=0;i<pra.length-1;i++)
{
tbody += '<td>';
if (pra[i]=="Red")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/down.png'/>");
}
else if (pra[i]=="Green")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
}
tbody += pra[i];
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
});
Any help will be appreciated. Thanks in advance.
You can build your header:
var header = "<th>...</th>";
Then:
$("table").append(header);
if I could get your point correctly
DEMO: http://jsfiddle.net/75zFX/8/
var colheader = '<tr><th>Column1</th><th>Column2</th> .....</tr>\n';
var tbody = colheader ;// and replace with var tbody = '';
If u want to add Header Manually to a Table,use this code.
JSP
<th id="example"></th>
JavaScript
$("#example").html("Header Value");

Categories