Take variable values and put them in another file - javascript

I'm coding the game blockly, I have a variable called lineCount which counts the number of line breaks. however this variable is in a file called lib-dialog.js. When I insert the value of this variable with innerHTML I can get the value of lines by creating a div in the soy.js file (File by which I need to treat the result) But I need this value in a variable to put an if(lines == 6) { }
// Add the user's code.
if (BlocklyGames.workspace) {
var linesText = document.getElementById('dialogLinesText');
linesText.textContent = '';
// Line produces warning when compiling Puzzle since there is no JavaScript
// generator. But this function is never called in Puzzle, so no matter.
var code = Blockly.JavaScript.workspaceToCode(BlocklyGames.workspace);
code = BlocklyInterface.stripCode(code);
var noComments = code.replace(/\/\/[^\n]*/g, ''); // Inline comments.
noComments = noComments.replace(/\/\*.*\*\//g, ''); /* Block comments. */
noComments = noComments.replace(/[ \t]+\n/g, '\n'); // Trailing spaces.
noComments = noComments.replace(/\n+/g, '\n'); // Blank lines.
noComments = noComments.trim();
var lineCount = noComments.split('\n').length;
var pre = document.getElementById('containerCode');
pre.textContent = code;
if (typeof prettyPrintOne == 'function') {
code = pre.innerHTML;
code = prettyPrintOne(code, 'js');
pre.innerHTML = code;
}
if (lineCount == 1) {
var text = BlocklyGames.getMsg('Games_linesOfCode1');
} else {
var text = BlocklyGames.getMsg('Games_linesOfCode2')
.replace('%1', String(lineCount));
}
linesText.appendChild(document.createTextNode(text));
document.getElementById("contarBloco").innerHTML = lineCount;
var contandoBloco = lineCount;
}
I need to take the variable lineCount and put its value in another js.but I'm only managing to insert it into a div with innerHTML

it is better you use localstorage . Set the value of localcount in the local storage and get wherever you want
var lineCount = noComments.split('\n').length;
localStorage.setItem("lineCount", lineCount); // in first file
var count = localStorage.getItem("lineCount") // in second file
with this logic you will get the value but it will be string then for that you either use directly string or convert into integer using parseInt method
parseInt(count);
may be it will help . Thanks

I don't know if your Javascript files are modules, if so, you can return a function in your lib-dialog.js page and return it.
Example
lib-dialog.js =
let Dialog = (function() {
function SetLineCountVariable(LocalLineCount){
LineCount = LocalLineCount;
}
return SetLineCountVariable
})();
And in your soy.js file
let Soy = (function() {
Dialog.SetLineCountVariable(6);
})();
And do not forgot to call your JS file in order in your HTML page
Another way, if you only want the variable result in your another JS file, in your lib-dialog.js, show the result of LineCount in html tag and get it in your another JS file with document.getElementById

Related

Alert showing when it shouldnt be (XML Parse)

<script>
async function loadData() {
var data = await fetch("Product.xml");
var parsedData = await data.text();
var parser = new DOMParser();
var Product_document = parser.parseFromString(parsedData,"text/xml");
var results = "";
var AlertBox = ""
var user_id_input = document.getElementById("user_id").value;
var todos = Product_document.getElementsByTagName("product");
for(var i = 0; i < todos.length; i++) {
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
var Code = todos[i].getElementsByTagName("Code")[0].childNodes[0].nodeValue;
var Quantity = todos[i].getElementsByTagName("Quantity")[0].childNodes[0].nodeValue;
var Description = todos[i].getElementsByTagName("Description")[0].childNodes[0].nodeValue;
var Price = todos[i].getElementsByTagName("Price")[0].childNodes[0].nodeValue;
if(user_id_input === Code) {
results = "<div>"
+ "Code: " + Code
+ ",<br/> Name: " + Name
+ ", <br/>Quantity: " + Quantity
+ ",<br/> Description " + Description
+ ",<br/> Price " + Price
+ "</div><br/>";
AlertBox= "True";
}
if(AlertBox !== "True") {
alert("Error");
}
}
document.getElementById("results").innerHTML = results;
}
</script>
I'm trying to code a web app that takes user input, parses an XML file and then displays some information. I have that part working.
My problem is, I want there to be an Error alert if the Input does not match any of the XML elements. I have coded one in, but for every element the app checks that doesn't match the user input the app is giving me an error alert. And I have no idea how to solve it.
enter image description here
I've tried adding a variable that changes to true if the input matches and only allowing the alert to show up if that variable is false and I still get the Alert.
enter image description here
Based on your code I think the reason why it is not working is the nodeValue property as this returns null.
When called on an element tag (nodeType 1) nodeValue returns null. nodeValue will return the actual text content when it is called from a text element (nodeType 3). The 'Code' tag is of type element and has a child of type text therefore you don't get the desired text value. You can read more on nodeType here.
To get the correct result from nodeValue you need to call it like this:
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].firstChild.nodeValue;.
As you want to get the text content from an element you can also use the following code instead:
var Name = todos[i].getElementsByTagName("Name")[0].childNodes[0].textContent;
The if condition should now also be executed correctly as long as the user_id_input variable has also the correct value. If the function loadData is executed before the user has entered values into the form fields, you need to execute the function when your form has been submitted. This way you can make sure that the user has entered values to all required fields. You can read more about HTML Forms and managing them via JavaScript here if needed.
I would also suggest to use let and const instead of var.
Additionally I think you would like to use your variable AlertBox as a boolean. If that is the case please use the boolean datatype in JavaScript. You can write it like this:
let AlertBox = false; or let AlertBox = true;

Split php varibale with JS into array

I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}

how to break up the content of a long text file to fit into multiple variables in google apps script?

I have a very long plain text file in my google drive which I need to parse through and select pieces of information through a script. I have successfully pulled out the text and put it into a string variable, but it is so long that the variable only contains about 1/6 of the full document.
This is the code I am using:
function f09ToSpreadsheet() {
var allFilesInFolder,cntFiles,docContent,fileNameToGet,fldr,
thisFile,whatFldrIdToUse;//Declare all variable at once
whatFldrIdToUse = '0B2O23fJ4nQLONlA4RlhuLWp0Y0k';
fileNameToGet = 'Copy of RS_Tionesta_1N.txt';//Assign the name of the file to get to a variable
//Get a reference to the folder
fldr = DriveApp.getFolderById(whatFldrIdToUse);
//Get all files by that name. Put return into a variable
//allFilesInFolder = fldr.getFilesByName(fileNameToGet);
allFilesInFolder = fldr.getFiles();
//Logger.log('allFilesInFolder: ' + allFilesInFolder);
if (allFilesInFolder.hasNext() === false) {
//If no file is found, the user gave a non-existent file name
return false;
};
cntFiles = 0;
//Even if it's only one file, must iterate a while loop in order to access the file.
//Google drive will allow multiple files of the same name.
while (allFilesInFolder.hasNext()) {
Logger.log("yup")
var thisFile = allFilesInFolder.next();
//KEY TO READING TEXT FROM .F05 & .F09 ->
docContent = thisFile.getAs("application/octet-stream");
var string = docContent.getDataAsString();
Logger.log('docContent : ' + string );
};
}
The "string" object, when printed to the log, only contains the first part of the text doc.
Is there any way to, say, split up the document into small pieces and store each part in a variable?
I'm afraid I've not tested this so apologies if it doesn't work straight away but could you get your document paragraph by paragraph and append the text like that?
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paras = body.getParagraphs();
paras.forEach(function( para ){
var text = para.getText();
populateSheet( text );
});

JavaScript FileReader and Dynamic Tables

I am trying to upload a file and read its contents and then output the contents to a table. The information needs to be place on a new row whenever there is a > char in the string.
I am having a bit of an issue wrapping my head around how I can create a new 'tr' and then add data to the a cell 'td' in that row.
I am stuck on the <tr> and <td> and adding them dynamically with the contents from the file. I am sure I can use regex to look for the > char but that isn't really what I need help with. I am struggling with how I take the information after the > char and add it to a new row in the table.
UPDATE: Ok, so I am still not fully functional on what I am trying to do. I am uploading the file, reading it, and storing the information as an object. However, I can only do this for one instance. When I upload a text file there will be multiple DNA sequences in the file. Each sequence will have a sequence_id like this:
9013e1
ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCC
CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGC
CTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGG
AAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCC
CTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAG
TTTAATTACAGACCTGAA
So, I am trying to read the file, find all sequence ID's and then sequences and I want an editable leading and trailing trim like so:
var objArray = [
{
'id': '>9013e1',
'sequence': 'ACAAGATGCCATTGTCCCCCGGCCT...',
'lead_trim': //get the value from a input from the user,
'trail_trim': //same as above
},
{
//another obj like above
}
]
The sequence also needs to have a line break inserted after every 60 characters. Once I have processed the data in the text file correctly I then need to output the data to a table like I stated in my original post. The problem I am having is I am getting stuck on only being able to store information for one obj in my objArray.
Here is a look at my code...
function scanForSequences(event) {
//Get the file from HTML input tag
var file = event.target.files[0];
var output = document.getElementById('table');
if(file) {
var sequenceArray = [];
var objArray = [];
var obj = {};
var str = '';
var subStr = '';
//Create a new file reader
var reader = new FileReader();
//When the file reader loads
reader.onload = function(evt) {
//Add the contents of file to variable contents
var contentsByLine = evt.target.result.split('\n');
//Alert user the file upload has succeeded
alert('File ' + file.name + ' has been uploaded!');
for(var i = 0; i < contentsByLine.length; i++){
if(contentsByLine[i].charAt(i) == '>'){
obj['id'] = contentsByLine[i];
}else{
sequenceArray.push(contentsByLine[i]);
str = sequenceArray.toString();
subStr += str.substring(0, 60) + '\n';
str = str.substring(60);
obj['sequence'] = subStr;
obj['lead_trim'] = 0;
obj['trail_trim'] = 0;
}
objArray.push(obj);
console.log(objArray);
}
}
reader.readAsText(file);
} else {
alert('Failed to upload file!');
}
console.log(obj);
}
document.getElementById('fileItem').addEventListener('change', scanForSequences, false);
Please find my proposed solution in the fiddle below:
https://jsfiddle.net/w6jbuqfy/
Here's an explanation of what's going on:
First we have a input of type file:
<input id="input" type="file">
We then attach an event listener to it to execute a function once a user has selected a file
var inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFile, false);
Inside the handleFile function, we use a FileReader to read the file.
var fileList = this.files;
var file = fileList[0];
var fr = new FileReader();
fr.readAsText(file);
Now fileReaders are asynchronous in nature, here i've got a simple interval that checks on the status of the filereader every 100ms.
var checkReadyId = setInterval(function(){
if(fr.readyState === 2){ //done
window.clearInterval(checkReadyId);
addFileDataToResults(fr.result);
} else{
console.log('not done yet');
}
}, 100);
FileReaders are done reading when their readyState is 2. So we check for that and once we are done, we can access the result from FileReader.result. As we read this as a text earlier above, we'll get a string back. We then pass this to our addFileDataToResults function.
function addFileDataToResults(fileAsString){
var resultsDiv = document.getElementById('results');
var tr = document.createElement('tr');
var td = document.createElement('td');
var linesInFile = fileAsString.split('\n');
console.log(linesInFile);
td.textContent = linesInFile[0];
tr.appendChild(td);
resultsDiv.appendChild(tr);
}
What is happening here is that we grab the resultsDiv which is a real node in our HTML. We then use createElement which creates virtual nodes and put data into them. IN this case, we are simply putting the text of the first line into our file. Once we are done creating this virtual nodes, we use appendChild to our real node which turns the virtual node into a real node and you can see it in the html.
Hope this helps
:)

TypeError: 'undefined' is not an object in Javascript

I have a piece of Javascript code that assigns string of values to a string array.
Unfortunately if I try to add more than one string to the array, my UI simulator(which runs on JS code) closes unexpectedly. I have tried debugging but I cannot find anything. I am attaching that piece of code where the issue is. may be you guys could find some flaw? On the pop up button click the values I selcted on the UI should get stored in the array and I have a corressponding variable on the server side to handle this string array.
_popupButtonClick: function (button) {
var solutions = this._stateModel.get('solutionName');
var i;
var solutionsLength = solutions.length;
var selectedSolution = [solutionsLength];
this.clearPopupTimer();
if (button.position === StatusViewModel.ResponseType.Ok) {
for(i=0;i<solutionsLength;i++)
{
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
this._stateModel.save({
selectedsolutions: selectedSolution,
viewResponse: StatusViewModel.ResponseType.Ok
});
} else {
this._stateModel.save({
viewResponse: StatusViewModel.ResponseType.Cancel
});
}
}
Change
var selectedSolution = [solutionsLength];
to
var selectedSolution = [];
This makes your array have an extra item that might be causing a crash.
Also,
you have an
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
But no corresponding else, so your array has undefined values for i which are not entering the if.
Maybe adding an empty string might solve it:
if(this._list.listItems[i].selected)
{
selectedSolution[i] = this._list.listItems[i].options.value;
}
else
{
selectedSolution[i] = "";
}
The code is looking fine but there seems to be a piece of code which can cause error. For example, you are assigning var selectedSolution = [solutionsLength]; and for example solutionsLength is 5 then your loop runs for 5 times
for(i=0;i<solutionsLength;i++) // runs for 5 times
{
if(this._list.listItems[i].selected)
{
// but selectedSolution = [5]; which is on 0th index and from 1st to 4th index it is undefined
selectedSolution[i] = this._list.listItems[i].options.value;
}
}
So you can try to use push() like
selectedSolution.push(this._list.listItems[i].options.value);
and on initialization change it like,
var selectedSolution = [];
Hopefully this will solve your problem.
var selectedSolution = [solutionsLength];
keeps the value in the selectedSolution variable.
var selectedSolution = [3];
selectedSolution[0] gives the values as 3
So make it simple
var selectedSolution = [];

Categories

Resources