Processing lines and filling fields - javascript

I read and search and study, but can't seem to write any JS out of my own head - this should be really simple but it will not work. I keep getting an error about an undefined variable "madlib7.html:411 Uncaught ReferenceError: populatefields is not defined at HTMLButtonElement.onclick"
I start with some urls that I paste into a textarea, then I click a button and first it splits the text into individual lines and stores them in variables. Next, I want to split each line by spaces and populate fields in an HTML form with select words from the resulting array via the use of innerhtml.
I know there is some way of looping through the processes, but I have not figured out how to do that yet so for now I am writing it all out the long way. I have not been able to figure out how to address the error message 'ReferenceError' from above.
Thanks for any and all help
Paul
populatefields(day1, location1, streamid1) {
document.getElementById('PanLinks').value.split('\n');
var streamInfoLine1 = resultArr[0];
var streamInfoLine2 = resultArr[1];
var streamInfoLine3 = resultArr[2];
var streamInfoLine1 = resultArr[3];
var streamInfoLine2 = resultArr[4];
var streamInfoLine3 = resultArr[5];
var streamInfoLine1 = resultArr[6];
var streamInfoLine2 = resultArr[7];
var streamInfoLine3 = resultArr[8];
streamInfoLine1.split(' ');
var day1 = resultArr[0];
var location1 = resultArr[3];
var streamID1 = resultArr[4];
document.getElementById("location1").innerHTML= location1;
document.getElementById("time1").innerHTML= day1;
document.getElementById("streamid1").innerHTML= streamID1;
}

could you use stackoverflow built in code sandbox to include all your code in html, javascript code? it seems like the issue is on your html file madlib7.html, where your onclick listener isn't defined on the button. nor did I see anything from your code that indicates any event listener has been setup to perform that button task. so it's hard to help debug what exactly it is.

Related

Random "Cannot read properties of null" error in Google Sheet with App Script

I have a Google sheet that automatically changes the urls in cell A28 via another script. The "test()" script is called by the main script to be executed whenever the url changes. I used the code from another thread: Grab data from website HTML table and transfer to Google Sheets using App-Script.
I modified it a bit because what interested me was getting the table with the ID "pgl_basic" and actually the code works as I expected. The only problem is that, in an absolutely random way, sometimes this error is generated: "Cannot read properties of null [0]" and if I then restart the script everything is fine or it crashes before or after the url it has determined the error, therefore it is absolutely random and without an apparent correlation.
function test() {
var tableHtml = 0;
var sheet = SpreadsheetApp.getActive().getSheetByName("2023");
var url = sheet.getRange("A27").getValue();
var html = UrlFetchApp.fetch(url, {muteHttpExceptions: true}).getContentText().replace(/(\r\n|\n|\r|\t| )/gm,"");
var tableHtml = html.match(/<table\s.*?id="pgl_basic"[\s\S]*?<\/table>/)[0];
var trs = [...tableHtml.matchAll(/<tr[\s\S\w]+?<\/tr>/g)];
var data = [];
for (var i=0;i<trs.length;i++){
var tds = [...trs[i][0].matchAll(/<(td|th)[\s\S\w]+?<\/(td|th)>/g)];
var prov = [];
for (var j=0;j<tds.length;j++){
donnee=tds[j][0].match(/(?<=\>).*(?=\<\/)/g)[0];
prov.push(stripTags(donnee));
}
data.push(prov);
}
return(data);
}
function stripTags(body) {
var regex = /(<([^>]+)>)/ig;
return body.replace(regex,"");
}
Initially the line:
var tableHtml = 0;
It didn't exist in the original code and I added it thinking it was a tableHtml variable "cache" issue but that didn't fix my problems. Using the code of the aforementioned topic, however, there is no problem or error but that code fetches all the tables included in the website and since they are not all the same, I don't need it but I need that specific table with that specific ID. I also tried to use a simple 2 second delay (via Utilities.sleep) thinking it could be a connection loading problem but this doesn't seem to be the case, also because I repeat that the original code (even with much larger data) works without a hitch. What could be the solution? Thanks.

handling new image file value is undefined in javascript

Working on a small guestbook posting site as part of a course however I've run into a little problem I cannot figure out.
Using a buttion to open file selection, to select an image and then process this file using the data url and create a key from the date.
However, during getting the file my data variable remains undefined all the way through and never receives the information it needs to show the image. and I'm unable to figure out the cause.
Below are the relevant parts.
function addPhotoClick() {
var inputElement = document.querySelector("#image input");
inputElement.click();
}
function processFile(event) {
debugger;
var data = event.target.result;
debugger;
var key = "diary" + Date.now();
debugger;
addImageEntry(key, data);
}
function initalize(){
var addPhotoButton = document.querySelector("#image button");
addPhotoButton.addEventListener("click", addPhotoClick);
}
Any help would be appreciated.
Try accessing file through image_field_id.files[0] instead of event. According to this, every browser which supports HTML5 should support this property.
Btw not sure if you need a button here, <input type="file"> should create one automatically.
And always add related HTML, please, it's not 100% clear how it looks like.

How to Sanitize JS Input

Hi I have a Java Script Code for handle Modals and some input data. Code is working fine but Now I have run into a problem after code scanning. Scanning tool is giving me the Client Potential XSS error and asking me to Sanitize my input.
Error Description:
Method $ at line 484 of public/js/Activity/dailyActivity.js gets user input for the attr element. This element’s
value then flows through the code without being properly sanitized or validated and is eventually displayed to
the user in method $ at line 484 of public/js/Activity/dailyActivity.js. This may enable a Cross-Site-Scripting
attack.
JS Code:
var job_id;
// Delete action
$(document).on("click", ".deleteButton", function() {
var jobcycid = $(this).attr("data-jobcycid");
job_id = $(this).attr("id");
$("#deleteModal").modal("show");
$("#jcId").html(jobcycid);
});
I'm not very good at JS and still at the beginner level. Can anyone tell me how to sanitize this input?
Scan report highlights the following lines:
....
485. var jobcycid = $(this).attr("data-jobcycid");
....
488. $("#jcId").html(jobcycid);
I've found a solution to this.
I have created following function to sanitize any variable generated from HTML value:
// Sanitize and encode all HTML in a user-submitted string
var sanitizeHTML = function(str) {
var temp = document.createElement("div");
temp.textContent = str;
return temp.innerHTML;
};
Then you can use that to sanitize the variable:
var jobcycid = sanitizeHTML($(this).attr("data-jobcycid"));

Loading a Random Caption from a text file using Javascript and Displaying via HTML

I am trying to load a random caption every time my page is loaded. I have a separate text file and contained on each line is a string. I am new to both html and Javascript, as you will see.
HTML:
<div class="centerpiece">
<h1>DEL NORTE BANQUEST</h1>
<p class="caption"><script src = "js/caption.js"></script><script>getCaption();</script></p>
<a class="btn" id="browse-videos-button" href="#video-list">Browse Videos<br><img src="img/arrow-down.svg"style="width:15px;height:15px;"></a>
</div>
Javascript:
function getCaption()
{
var txtFile = "text/captions.txt"
var file = new File(txtFile);
file.open("r"); // open file with read access
var str = "";
var numLines = 0; //to get the range of lines in the file
while (!file.eof)
{
// read each line of text
numLines += 1;
}
file.close();
file.open("r");
var selectLine = Math.getRandomInt(0,numLines);//get the correct line number
var currentLine = 0;
while(selectLine != currentLine)
{
currentLine += 1;
}
if(selectLine = currentLine)
{
str = file.readln();
}
file.close();
return str;
}
Text in Source File:
We talked yesterday
Freshman boys!
5/10
I'm having a heart attack *pounds chest super hard
The site is for my highschool cross country team in case the text file was confusing.
I am unfamiliar with most syntax and was unable to see if by iterating through the file with a loop if i needed to reset somehow which is why I opened and closed the file twice. Here is a jsfiddle of the specific caption I am trying to change and what my function is in Javascript.
https://jsfiddle.net/7cre9qqj/
If you need more code to work with please let me know and any critiques you may have please dont hold back if it looks like a mess, I am trying to learn after all! Thank you for your help!
The File API allows access to the file system on the client side, so it's not really suited to what you want to do. It's also only allowed to be used in very specific circumstances.
A simple solution is to just run an AJAX request to populate your quote. The AJAX call can read the file on your server, then it's simple to split the contents of the file by line, and pick a random line to display. Since you're open to jQuery, the code is pretty simple:
$.get("text/captions.txt")).then(function(data) {
var lines = data.split('\n');
var index = Math.floor(Math.random() * lines.length);
$("#quote").html(lines[index]);
});
Here's a fiddle that demonstrates it in full; every time it runs it will load a random quote: https://jsfiddle.net/s1w8x4ff/

Removing Edit Access from a Sheet using email from a cell

I am trying to figure out how to remove someone from a spreadsheet using google app scripts.
Essentially, I have a central spreadsheet with information such as emails, names, UID's etc on it. I am trying to pull the email from this spreadsheet and use the removeEditor function to remove that email from another spreadsheet. You can view the code below.
var officerIDrow = officerID + 1;
var Tracker = SpreadsheetApp.getActive().getSheetByName('P_Tracker'); //the button is on the same sheet as this, this is why it is get active.
var PTBooking = SpreadsheetApp.openById("1JPS69ko99dQTEwjplF_l2l2G_T8RyHjxCyMxXd_AV_s"); //Referring to the other sheet where the email will be removed from editors.
var EmailAddressRange = "F" + officerIDrow; //This is the column where the emails are stored. The officer ID row refers to the user inputted value in a dialog. Don't worry about this, I have already checked to see if this is the issue,
var EmailAddress1 = Tracker.getRange(EmailAddressRange);
var EmailAddress2 = EmailAddress1.getValue();
var EmailAddress3 = Utilities.formatString(EmailAddress2); //In my desperation, I was trying to see if setting it as string would help.
PTBooking.removeEditor(EmailAddress3);
This isn't the full version of the code. If you'd like to see it, you can click here. But all that matters is above, everything else works fine.
The code above runs fine until it hits the last line where it tries to remove the email. The error message that appears says: "Invalid email: ". I'm assuming after the "email:" bit, it should display what has been pulled. But it doesn't! I have no idea why it isn't finding and using the email to remove people.
Can anyone spot any issues?
Thanks,
Shaun.
This basic test worked for me. It could read email address from the spreadsheet then remove editors from the external sheet. I tried to copy your example, but I don't know how the officerIDrow works, but I assume it's a number. So just stored a number as a var
function myTest() {
var ss = SpreadsheetApp.openById("ID HERE");
var idRow = 11;
var tracker = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("tracker");
var emailCell = "F"+idRow;
Logger.log(emailCell);
var emailAddress = tracker.getRange(emailCell).getValue();
Logger.log(emailAddress);
ss.removeEditor(emailAddress);
var editors = ss.getEditors();
Logger.log(editors);
}
I've left the Logger bits in as it will help point you at what script is doing at each point.
The email address in the cell must be plain, such as google#google.com

Categories

Resources