JavaScript: getting undefined variable message but variable is defined (I think) - javascript

I'm relatively new to JavaScript, although I have recently turned a corner. I just wrote this code block to validate an email field that's generated by a CMS, but I'm getting a message that invalidEmailMsg is undefined. I have tried placing the variable declaration inside the function, outside the function, inside the if statement (basically flailing my arms around), but the message persists. Can anyone help? Please and thank you.
var email = document.getElementById("trouble-tickets-email");
email.addEventListener("keyup", function() {
var invalidEmailMsg = document.forms[1].getElementsByClassName("form-error-msg")[3];
var emailValue = email.value;
var emailPattern = /.+#.+\..+/;
if(emailPattern.test(emailValue) === false) {
invalidEmailMsg.css.style("display","block");
invalidEmailMsg.innerHTML = "custom message";
}
});

Related

'checked' with if statement does not work properly

Hi guys i am making calculator app and i have got a problem.
I made 3 radio buttons and want them to be checked with 'if statement' in JS file. It just does not work at all because 'main' does not get any class when input2 or 3 is clicked. Only the first one makes 'main' getting it but thats because of input1.checked defaultly set to true. Can anyone help me, pls?
Here is the link to the project on my github:
https://github.com/Adrian397/frontEndMentorChallenges/tree/master/calculator-app-main
Here is live site of it: https://adrian397.github.io/frontEndMentorChallenges/calculator-app-main/index.html
js file
html file
Really liked your idea with different themes.
Coming to your query.
Looks like you have been using const for the main variable. Hence you won't be able to change it.
It would help if you can change the variables to var or let.
Note : Always use const when you are sure that you are not going to change that variable.
Also, its a great habit if you can use :
if(document.getElementById('input1').checked) {
document.getElementById("main").innerHTML
= <Your code goes here>
}
This simplifies the process and keeps the source clean for one Page applications.
Hope this helps. May the source be with you !
Before all, at the first line of your js code you are declaring let main= document.querySelector('main');
This cannot works there because a variable declared as let can be visible only in the function where it is declared so
It's not in the scope of your function declared later (Not visible to it)
then you are declarig input as const and it could give some problem because a constant cannot update so the state checked should be always the same
your code corrected should be this
document.addEventListener("DOMContentLoaded", ()=>{
let main = document.getElementById("main");
let firstInput = document.getElementById("input1");
let secondInput = document.getElementById("input2");
let thirdInput = document.getElementById("input3");
if(firstInput.checked == true){
main.classList.add('dark');
}else {
main.classList.remove('dark');
}
});
Just add the other 'if' like this above.
Also give an id to the html element main to get it from id
I got help on another post so here im pasting corectly working code:
let input1 = document.getElementById("input1");
let input2 = document.getElementById("input2");
let input3 = document.getElementById("input3");
let main = document.getElementById("main");
input1.checked = true;
function setColorTheme() {
if (input1.checked == true) {
main.classList.add("dark");
} else {
main.classList.remove("dark");
}
if (input2.checked == true) {
main.classList.add("light");
} else {
main.classList.remove("light");
}
if (input3.checked == true) {
main.classList.add("saturated");
} else {
main.classList.remove("saturated");
}
}
setColorTheme();
document.querySelectorAll('input[name="theme"]').forEach((e) => {
e.addEventListener("change", setColorTheme);
});
The problem was solved by adding these lines and making variables declarations using 'let':
document.querySelectorAll('input[name="theme"]').forEach((e) => {
e.addEventListener("change", setColorTheme);
});

ncaught TypeError: Cannot read property 'push' of undefined at generatePassword (tutor.js:103)at HTMLButtonElement.writePassword (tutor.js:113)

So, I've never come across the Violation error before. Not really understanding what is going wrong. I'm learning so any helpful hint would be awesome.
I'm sure that all of this should work just not sure where i'm going wrong at the moment.
var generateBtn = document.querySelector("#generate");
function getOptions() {
// Creating a random element from selected array
function generatePassword() {
// Looping through to create a new password
for (var i = 0; i < userOptions.length; i++) {
newPassword.push(getRandomElement(masterArr));
};
console.log(newPassword);
return newPassword;
};
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
};
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
I was provide the button code from class. so I'm pretty sure that is good code. Although it seems like that is where the errors seem to be coming in. I'm also not sure why the newPassword.push has an error.

How to fix 'TypeError: Cannot call method "getMessages" of undefined.'

I just joined a company and I'm having issues with a script written by someone who no longer works here. I keep receiving a TypeError. I'm also new to this code.
I've gone through some other threads and didn't see anything related to this particular TypeError.
function csatGmailPull() {
var threads = GmailApp.search("label: name");
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
if (attachment.getContentType() === "text/csv") {
var sheet = SpreadsheetApp.openById("SheetID").getSheetByName('Import');
var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");
sheet.clearContents().clearFormats();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
var labelOld = GmailApp.getUserLabelByName("LabelName");
var labelNew = GmailApp.getUserLabelByName("LabelName2");
threads[0].addLabel(labelNew);
threads[0].removeLabel(labelOld);
}
}
I've removed the sheet ID and label names. But this code is supposed to open up Gmail, get the emails under the label identified in the GmailApp.search, load the data into a preset Google Spreadsheet, and then tag the message with a new label. However, I keep getting "TypeError: Cannot call method "getMessages" of undefined." when I test it. Any help would be appreciated!

Google Script not Appending Spreadsheet

I'm trying to write a little script to make my coworkers and mine lives easier. I am trying to append lines to a spreadsheet based on information entered into a custom form. The code posted below just the doPost block which should be appending the google spreadsheet.
function doPost(form) {
var PN = form.PartNumber;
var REV = form.Revision;
var DATE = form.RevisionDate;
var DESC = form.Description;
var NOTE = form.PartNotes;
var URL = form.myFile.getURL();
var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
var sheet = ss.getSheetName('Uploads');
sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}
I am unsure why it isn't writing to the spreadsheet but it isn't throwing me any errors. If you can offer any insight as to what is wrong I would greatly appreciate it; there are many guides online but most seem to be based on deprecated functions/code/etc.
Thanks for your time.
Instead of using doPost, set up a "On form submit" trigger.
You need to get the namedValues to be able to pull specific values and take the first output.
Also, it should be "getSheetByName('Uploads')" .
As pointed out in the previous answer, it is unclear what you are trying to achieve by "form.myFile.getURL();" If you want to get the form url you might as well create it as a string, as it always stays the same.
Here is a working example of your code:
function doPost(form) {
var formResponses = form.namedValues;
var PN = formResponses.PartNumber[0];
var REV = formResponses.Revision[0];
var DATE = formResponses.RevisionDate[0];
var DESC = formResponses.Description[0];
var NOTE = formResponses.PartNotes[0];
//var URL = form.myFile.getURL(); //Not sure what you are tyring to get here as form URL will always be the same.
var URL = "Your form's url"; //You can put the form url in here so it will be pushed in to every row.
var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
var sheet = ss.getSheetByName('Uploads');
sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}
The form fields are nested in a "parameter" property in the doPost parameter.
So, you should access them using:
function doPost(form) {
var actualForm = form.parameter;
var PN = actualForm.PartNumber;
//etc
To double check all parameters your receiving and their names, you could append to your sheet everything stringfied, like this:
sheet.appendRow([JSON.stringify(form)]);
--edit
This form.myFile.getURL() also looks odd. I guess another good debugging trick you could do is to wrap everything in a try-catch and email yourself any errors you get. For example:
function doPost(form) {
try {
//all your code
} catch(err) {
MailApp.sendMail('yourself#etc', 'doPost error', err+'\n\n'+JSON.stringify(form));
}
}
On form submit
onFormSubmit works. "doPost" looks wrong.
Simple example:
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendGoogleForm(e)
{
try
{
Full example - Scroll down to the code http://www.labnol.org/internet/google-docs-email-form/20884/ (Note: example sends email)
Trigger docs: https://developers.google.com/apps-script/guides/triggers/events
Notes: I think the problem is doPost, Does it work with google Forms? Never seen it used with google forms.
First and foremost, thank you everyone who has responded with information thus far. None of the solutions posted here worked for my particular implementation (my implementation is probably to blame, it is very crude), but they definitely set me down the path to a working version of my form which we now lightly use. I have posted some of the code below:
function sheetFill(form, link) {
try {
var formResponses = form.namedValues;
var toForm = [0,0,0,0,0,0,0];
for (i=0;i < form.PartNumber.length;i++){
toForm[0] = toForm[0]+form.PartNumber[i];
}
... (several for loops later)
var d = new Date();
var ss = SpreadsheetApp.openById("IDHERE");
var sheet = ss.getCurrentSheet;
ss.appendRow([toForm[0], toForm[1], toForm[2], toForm[3], toForm[4], toForm[5], toForm[6], link, d]);
} catch(err) {
MailApp.sendEmail('EMAIL', 'doPost error', err+'\n\n'+JSON.stringify(form));
}
}
It is not very versatile or robust and isn't elegant, but it is a starting point.

CRM Error Object doesn't support property or method 'getValue'

I'm starting to write a simple javascript on CRM Contact page to retrieve the parent account ID.
I set the script as an onChange event on the parent account field (parentcustomerid) and set it to "pass execution context as parameter".
This is my code:
function PopulateAccountType(ParentAccount) {
if (ParentAccount != null) {
var Account = new Array();
var Account = Xrm.Page.getAttribute("parentcustomerid").getValue();
{
var AccountId = Account[0].id;
}
}
}
Not sure why I keep getting error on the OnChange event Object doesn't support property or method 'getValue'.
I've been using 'getValue' function successfully but is it different when the value is an ID?
Thanks for your help, greatly appreciate.
-elisabeth
Try this Code and Uncheck Execution Parameter Check Box.
function PopulateAccountType()
{
var lookup = Xrm.Page.getAttribute("parentcustomerid").getValue();
if(looup!=null)
{
var Account = lookup[0].id;
alert(Account);
}

Categories

Resources