Creating Navigation from text file - javascript

i have following peice of code...
but showing error *Uncaught type reference Cannot call method 'split' of undefined *
<script src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var textFile = "nav.txt";
jQuery.get(textFile, function (textFileData) {
var EachLineInTextFile = textFileData.responseText.split("\n");
for (var i = 0, len = EachLineInTextFile.length; i < len; i++) {
STORE_TO_REPLACE = EachLineInTextFile[i];
//STORE_TO_REPLACE: I would have to the entire format of your file to do this.
console.log(STORE_TO_REPLACE);
}
})
});
</script>
nav.txt file is below
a a.aspx
b b.aspx
c c.aspx

Remove the .responseText part.
$(document).ready(function () {
var textFile = "nav.txt";
jQuery.get(textFile, function (textFileData) {
var EachLineInTextFile = textFileData.split("\n");
for (var i = 0, len = EachLineInTextFile.length; i < len; i++) {
STORE_TO_REPLACE = EachLineInTextFile[i];
//STORE_TO_REPLACE: I would have to the entire format of your file to do this.
console.log(STORE_TO_REPLACE);
}
})
});

Related

Unexpected quoted property in dynamically created object

I try to load contents of the CSV file into the array of JavaScript objects. Unfortunately, structure of data is not flat, so to mitigate that, I use dot-separated property names as column headers in CSV file. Example CSV file looks as follows:
codes.code1,codes.code2,codes.code3,codes.code4,info.description.text,info.description.language
49074202,64,1443,1416,Test description: 49074202 64 1443 1416,EN
81905948,10,9721,5411,Test description: 81905948 10 9721 5411,EN
87262350,86,7050,4775,Test description: 87262350 86 7050 4775,EN
The object structure I would like to end up with looks like
{
codes: {
code1: "49074202",
code2: "64",
code3: "1443",
code4: "1416"
},
info: {
description: {
text: "Test description: 49074202 64 1443 1416",
language: "EN"
}
}
}
Following code can be used to recreate the problem (using CSV file with contents posted above).
<html>
<body>
<form>
<input type="file" id="files" onchange="loadFromFile()" />
<script>
function loadFromFile() {
var selectedFile = document.getElementById('files').files[0];
var reader = new FileReader();
reader.onload = loadRowsFromFile;
reader.readAsText(selectedFile);
};
function loadRowsFromFile(e) {
var rows = e.target.result.split("\n");
if (!rows || rows.length === 0) {
return;
}
var headers = rows[0].split(",");
var loadedData = [];
for (var i = 1; i < rows.length; i++) {
var columns = rows[i].split(",");
var rowData = {};
for (var j = 0; j < headers.length; j++) {
placeElementInHierarchy(rowData, headers[j], columns[j]);
}
loadedData.push(rowData);
}
console.log(loadedData);
}
function placeElementInHierarchy(rowData, propertyPath, value) {
var path = propertyPath.split(".");
var obj = rowData;
for (var i = 0; i < path.length; i++) {
if (i === path.length - 1) {
obj[path[i]] = value;
} else {
if (!obj[path[i]]) {
obj[path[i]] = {};
}
obj = obj[path[i]];
}
}
}
</script>
</form>
</body>
</html>
File parsing works properly, data is loaded correctly into the structure. However, for some reason the last processed property name is quoted. Structure of all rows I obtain looks like that:
{
codes: {
code1: "49074202",
code2: "64",
code3: "1443",
code4: "1416"
},
info: {
description:{
text: "Test description: 49074202 64 1443 1416",
"language": "EN"
}
}
}
The only lead I have right now is that if I remove the 'language' column from CSV file, then 'text' is being quoted instead - so the last processed property is for some reason quoted. Thanks in advance!
EDIT: Fixed mistakes in the expected structure.
EDIT2: What is interesting, following code (skipping file upload part), doesn't show such symptoms
<html>
<body>
<form>
<script>
(function() {
var csvData = 'codes.code1,codes.code2,codes.code3,codes.code4,info.description.text,info.description.language\n' +
'49074202,64,1443,1416,Test description: 49074202 64 1443 1416,EN\n' +
'81905948,10,9721,5411,Test description: 81905948 10 9721 5411,EN\n' +
'87262350,86,7050,4775,Test description: 87262350 86 7050 4775,EN';
loadRowsFromFile(csvData);
})();
function loadRowsFromFile(csvData) {
var rows = csvData.split("\n");
if (!rows || rows.length === 0) {
return;
}
var headers = rows[0].split(",");
var loadedData = [];
for (var i = 1; i < rows.length; i++) {
var columns = rows[i].split(",");
var rowData = {};
for (var j = 0; j < headers.length; j++) {
placeElementInHierarchy(rowData, headers[j], columns[j]);
}
loadedData.push(rowData);
}
console.log(loadedData);
}
function placeElementInHierarchy(rowData, propertyPath, value) {
var path = propertyPath.split(".");
var obj = rowData;
for (var i = 0; i < path.length; i++) {
if (i === path.length - 1) {
obj[path[i]] = value;
} else {
if (!obj[path[i]]) {
obj[path[i]] = {};
}
obj = obj[path[i]];
}
}
}
</script>
</form>
</body>
</html>
Okay. As you can see in screen above, your problem is generated by Carriage Return character \r on end of every line in the file. You can remove all your empty characters from string using
trim()
or you can use regexp to cut out just this type of characters.
Example is done here:
How to remove all line breaks from a string?

HtmlService: google.script.run not recognizing gs function

I'm currently trying to pass an array of values from a Google Sheet to the HtmlService where I will have the user choose an option and eventually pass it back to the .gs script. I have been using these two links as references:
1. Google Documentation
2. Stack Overflow example
When running the code, I looked at my console and noticed this error:
VM3051:4 Uncaught TypeError: google.script.run.withSuccessHandler(...).getVersionArray is not a function
It appears that getVersionArray() is not being passed correctly. When removing this function from the rest of that google.script.run call, the error goes away.
Also, per link two, I tried that code with the template and never even got a window to pop up, so I have been using the HtmlOutput example from the Google documentation link as a starting point. I have also tried the code with and without the SandboxMode declaration.
gs code:
function bugPieChart() {
getVersionArray();
openDialog();
function getVersionArray() {
var ss = SpreadsheetApp.getActive();
var valuesR = ss.getSheetByName("report").getRange('R1:R').getValues();
var valuesS = ss.getSheetByName("report").getRange('S1:S').getValues();
var versionRSArray = [];
for (var i = 0; i < valuesR.length; i++) {
versionRSArray.push(valuesR[i][0]);
}
for (var i = 0; i < valuesS.length; i++) {
versionRSArray.push(valuesS[i][0]);
}
versionRSArray.sort();
var uniqueArray = [];
uniqueArray.push(versionRSArray[0]);
for (var i in versionRSArray ) {
if((uniqueArray[uniqueArray.length-1]!=versionRSArray[i]) && (versionRSArray[i] !== "")) {
uniqueArray.push(versionRSArray[i]);
}
}
return uniqueArray;
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
var htmlOutput = html.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}
}
index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOptionsList)
.getVersionArray();
});
function buildOptionsList(uniqueArray) {
var list = $('#optionList');
list.empty();
for (var i = 0; i < uniqueArray.length; i++) {
list.append('<option value="' + uniqueArray[i].toLowerCase() + '">' + uniqueArray[i] + '</option>');
}
}
</script>
</head>
<body>
<select id="optionList">
<option>Loading...</option>
</select>
<input type="button" value="Close" onclick="google.script.host.close()" />
</body>
</html>
I think your just missing a closing bracket on the function above it.
function bugPieChart() {
getVersionArray();
openDialog();
}
function getVersionArray() {
var ss = SpreadsheetApp.getActive();
var valuesR = ss.getSheetByName("report").getRange('R1:R').getValues();
var valuesS = ss.getSheetByName("report").getRange('S1:S').getValues();
var versionRSArray = [];
for (var i = 0; i < valuesR.length; i++) {
versionRSArray.push(valuesR[i][0]);
}
for (var i = 0; i < valuesS.length; i++) {
versionRSArray.push(valuesS[i][0]);
}
versionRSArray.sort();
var uniqueArray = [];
uniqueArray.push(versionRSArray[0]);
for (var i in versionRSArray ) {
if((uniqueArray[uniqueArray.length-1]!=versionRSArray[i]) && (versionRSArray[i] !== "")) {
uniqueArray.push(versionRSArray[i]);
}
}
return uniqueArray;
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Dialog title');
var htmlOutput = html.setSandboxMode(HtmlService.SandboxMode.NATIVE);
return htmlOutput;
}

Store and get value from one function to another function

I have a html page and I'm calling a javascript function from the html page and the script is in separate file
HTML
Click Me
<script src="Externalscript.js"></script>
<script>
Initialize('1,2,3,4');
</script>
JavaScript
var myList; //global variable
function Initialize(ids) {
myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++) {
myList.push(idList[i]);
}
I'm storing the ids value in myList and now I want to retrieve the myList when the button clicked
function ButtonClick() {
alert(myList);
}
Now, when I'm trying to alert the myList it is giving undefined.
How can store the values in a global variable and retrieve in other function
return the value from function than updating global-variable and accessing it
function ButtonClick() {
var returned = Initialize('1,2,3,4');
console.log(returned);
}
function Initialize(ids) {
var myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++) {
myList.push(idList[i]);
}
return myList;
}
Click Me
Edit: To store the result in global-variable
var returned = Initialize('1,2,3,4');
function ButtonClick() {
console.log(returned);
}
function Initialize(ids) {
var myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++) {
myList.push(idList[i]);
}
return myList;
}
Click Me
<!DOCTYPE html >
<html>
<head>
<script>
Initialize('1,2,3,4');
var myList; //global variable
function Initialize(ids)
{
myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++)
{
myList.push(idList[i]);
}
}
function ButtonClick()
{
alert(myList);
}
</script>
</head>
<body>
Click Me
</body>
</html>
I just rewrote your code and it prints the list as 1,2,3,4 as expected
I'm having trouble reconstructing the problem. Is this how your code looks like:
Click Me
<script>
var myList; //global variable
function Initialize(ids) {
myList = new Array();
var idList = ids.split(',');
for (i = 0; i < idList.length; i++) {
myList.push(idList[i]);
}
}
Initialize('1,2,3,4');
</script>
http://codepen.io/calvinclaus/pen/WxNaPX?editors=1011
Because this works...Can you supply a pen with the problem
?
Your code should work.
One advice: split already creates an array: MDN
So what you're doing is:
create an array from a string (idList = ids.split(','))
loop over that array
add every value from that array to a other array (myList.push(idList[i]);)
Where myList = ids.split(','); is enough
Example
var myList;
function Initialize(ids) {
myList = ids.split(',');
}
Initialize('1,2,3,4');
function ButtonClick(e) {
e.preventDefault();
alert(myList);
}
document.getElementById('btn1').addEventListener('click', ButtonClick);
Working demo: fiddle

Javascript doesn't work when have another one

I searched but I didn't find the answer.
I have a code that change the color of my wordpress template blocks and posts randomly. Actually it changes the classes of these blocks and so the colors. You can see the code here:
function inArray(array , exist) {
var rslt = false;
for (var j = 0; j < array.length; j++)
{
if (array[j] == exist)
{
rslt = true;
}
}
return rslt;
}
var colored = Array();
function changeColor(target) {
var blocks = document.getElementsByClassName(target);
var blockLength = blocks.length;
for (var i = 0; i < blockLength; i++)
{
if (colored.length >= 9)
{
colored = [];
}
var rand = 0;
while (rand == 0 || inArray(colored , rand))
{
rand = Math.floor(Math.random()*10)%10;
}
colored.push(rand);
blocks[i].className = target+' color'+rand ;
}
}
window.onload = function() {
changeColor('block');
changeColor('post');
}
the code you seen placed in an external file named 'colors.js' and included by:
<script src="<?php bloginfo('template_url'); ?>/scripts/colors.js"></script>
in my wordpress template.
the code works correctly til I add another code like this:
<script>var _mxvtmw_position = 'left', _mxvtmw_domain = 'icomp.ir'</script>
<script src="http://iwfcdn.iranwebfestival.com/js/mx.vtmw.min.js?12688" async="async"></script>
Why? And how can i fix this problem?
Thank you.
EDIT:
DEMO: http://tuts.icomp.ir/
IN CASE blocks.length IS 1 YOU HAVE TO ADD ONE MORE IF CONDITION
if (blocks.length==undefined){
//code
}

Problems with multidimensional array and loops

This script crashes randomly with the message "unable to get property .length of undefined or null reference" referring to "matched_array_pics.length". It crashes for sure if I clone, append the same image twice to the #train div.
$(document).ready(function () {
var starting_pics = ["AN.gif", "CN.gif", "EN.gif", "GN.gif"];
var an_array_pics = ["CN.gif", "EN.gif", "GN.gif", "AN.gif"];
var cn_array_pics = ["EN.gif", "GN.gif", "AN.gif", "CN.gif"];
var en_array_pics = ["GN.gif", "AN.gif", "CN.gif", "EN.gif"];
var gn_array_pics = ["AN.gif", "CN.gif", "EN.gif", "GN.gif"];
var grand_array_pics = [an_array_pics, cn_array_pics, en_array_pics, gn_array_pics];
var i = 0;
for (i = 0; i < starting_pics.length; i++) {
$("<img/>").attr("src", "images/" + starting_pics[i]).load(function () {
$(this).appendTo("#main");
$(this).addClass("pics");
});
}
$("#main").on("click", ".pics", function () {
var j = $(".pics").index(this); // gets the index for the matched_array_pics...
console.log(j);
$("#sidebar .pics").remove();
$(this).clone().appendTo("#train");
$(this).clone().appendTo("#sidebar");
$("#main .pics").remove();
var matched_array_pics = grand_array_pics[j]; // ... in grand_array_pics.
var k = 0;
for (k = 0; k < matched_array_pics.length; k++) {
$("<img/>").attr("src", "images/" + matched_array_pics[k]).load(function () {
$(this).appendTo("#main");
$(this).addClass("pics");
});
}
});
}); //end ready
I think the problem is in this line: var j = $(".pics").index(this); and I think it should be rewritten like this: var j = $(this).index(); It'd be helpful if you could add console.log(j); just after the line in question to see what j ends up being. When this line executes var matched_array_pics = grand_array_pics[j]; I think you're getting undefined because j is not a number when your code runs.

Categories

Resources