JavaScript search not allowing for zero - javascript

Please see the Sample Fiddle
If you enter either of the example codes in the search box, you'll get a result that pops up in a jQuery UI Dialog.
The first example is 006.
Here's the code...
if (ccode == 006) {
sarcomment = '006';
sardefinition = 'If you need to make corrections to your information, you may either make them online at www.fafsa.gov, or by using this SAR. You must use your Federal Student Aid PIN to access your record online. If you need additional help with your SAR, contact your school’s financial aid office or visit www.fafsa.gov and click the “Help” icon on the FAFSA home page. If your mailing address or e-mail address changes, you can make the correction online or send in the correction on your SAR. ';
saractionneeded = 'N/A';
}
Immediately after that, you'll see the code for code 030.
Here's the code...
if (ccode == 030) {
sarcomment = '030';
sardefinition = 'We are unable to read all of the information on your FAFSA or SAR because it was damaged. Please review all of the items on this SAR and make any corrections as needed.';
saractionneeded = 'N/A';
}
The set up for the code 006 and 030 are the same. What I've learned here is that any of these search criteria that I create that ends with a 0 (zero), will result in an undefined query.
Not sure how to resolve this and seeking your assistance.

Numbers that begin with a 0 in old & backward compatible versions of JavaScript are octal.
030 = 0*8^2 + 3*8^1 + 0*8^0 = 24
Strict mode turns octal numbers into a syntax error

Here's a suggestion for cleaning up that code. Instead of a long train of if statements — each one of which provides a chance for some subtle bug to creep in — you could instead use an object to map codes onto blocks of information. That would look something like this:
function showc_code(ccode){
var codeTable = {
'006': {
definition: 'If you need to make corrections to your information, you may either make them online at www.fafsa.gov, or by using this SAR. You must use your Federal Student Aid PIN to access your record online. If you need additional help with your SAR, contact your school’s financial aid office or visit www.fafsa.gov and click the “Help” icon on the FAFSA home page. If your mailing address or e-mail address changes, you can make the correction online or send in the correction on your SAR. ',
action: 'N/A'
},
'030': {
definition: 'We are unable to read all of the information on your FAFSA or SAR because it was damaged. Please review all of the items on this SAR and make any corrections as needed.',
action: 'N/A'
},
'040': {
definition: 'Whatever',
action: 'Something something'
},
// ... other codes ...
};
if (codeTable[ccode] != null) {
sarcomment = ccode;
sardefinition = codeTable[ccode].definition;
saractionneeded = codeTable[ccode].action;
}
else {
// unknown code ... do whatever
}
// ... rest of your code to show the dialog ...
}
That way the mapping from code to relevant information is just data, with no "moving parts".

Related

Script to label emails if it contains specific words in the subject or body on Gmail

Update:
Thank you so much endothermic_dragon! You are brilliant! It all works now.
I have created scripts before but never for Gmail. I am having a hard time creating a script to filter emails coming in and label and archive them if they have specific words. We receive about 100 emails daily from various senders relating to a group of companies. Each company has its label. Usually the name of the company is in the subject or body of the email. I am trying to build a script that gets each email, check if the array with subjects or the array with plainBody contains the name of one or more of the labels (each label is the name of a company) in the labels array from getUserLabels(), and if so, assign the respective label(s) to it. I have tried everything, from filter() to forEach() to indexOf() but nothing seems to work. I feel the arrays from getUserLabels() and getInoboxThreads() are 2D, and I'm struggling to work with them. I've rewritten the code multiple times and it got me nowhere. I really hope one of you can shed some light on this.
Example:
Let's suppose we work with Apple, Amazon and Netflix. Each of these companies have their own label.
If an email comes in and has "Apple" in the subject or body, then add label "Apple" to it and archive it. If it has "Amazon" and "Netflix" in the subject or body, then add labels Amazon and Netflix.
Final code:
function labelEmails() {
var labels=[]
GmailApp.getUserLabels().forEach(function(label){labels.push(label.getName())})
var threads = GmailApp.search('is:unread').forEach(function(email){
email.getMessages().forEach(function(thread){
//Filter - https://developers.google.com/apps-script/reference/gmail/gmail-message
//Example used - if body contains 'hi', mark as read.
labels.forEach(function(label){
if (thread.getBody().toLowerCase().includes(label.toLowerCase())){
labelToAssign = GmailApp.getUserLabelByName(label);
labelToAssign.addToThread(email)
} else if (thread.getSubject().toLowerCase().includes(label.toLowerCase())) {
labelToAssign = GmailApp.getUserLabelByName(label);
labelToAssign.addToThread(email)
}
})
})
});
}
Some of our labels are abbreviations of the name of the companies, so I also needed a function to handle those. You can check it out below too:
(Companies in the code are random companies, not the real ones)
function labelExceptions() {
var exceptions = [{exc:'apple', labeln: 'APPL'}, {exc: 'amazon', labeln: 'AMZ'}, {exc: 'Bank of America', labeln: 'BOFA'}]
var threads = GmailApp.search('is:unread').forEach(function (thread){
thread.getMessages().forEach(function(message){
exceptions.forEach(function(exception){
if (message.getBody().toLowerCase().includes(exception.exc)){
labeltoAssign = GmailApp.getUserLabelByName(exception.labeln);
labeltoAssign.addToThread(thread)
} else if (message.getSubject().toLowerCase().includes(exception.exc)){
labeltoAssign = GmailApp.getUserLabelByName(exception.labeln);
labeltoAssign.addToThread(thread)
}
})
})}
);
}
Thank you very much!
Checked with my gmail, works!
function myFunction() {
var labels=[]
GmailApp.getUserLabels().forEach(function(label){labels.push(label.getName())})
var threads = GmailApp.search('is:unread').forEach(function(email){
email.getMessages().forEach(function(thread){
//Filter - https://developers.google.com/apps-script/reference/gmail/gmail-message
//Example used - if body contains 'hi', mark as read.
labels.forEach(function(label){
if (thread.getBody().toLowerCase().includes(label.toLowerCase())){
email.markRead()
}
})
})
});
}

Add confirm prompt in another language

How to add the confirm Prompt and Good bye message in another language based on user choice of language. Lets say I want to add a spanish version thats says goodbye
.cancelAction(
"cancelRequest", "Thank you for reaching out, Good bye!",
{
matches: /^nevermind$|^cancel$|^cancel.*request/i,
confirmPrompt: "This will cancel your request. Are you sure?"
}
);
You can do this using a variable which value is set depending on the language. This variable can then be used to get the corresponding text from an object.
For example:
var language = "spanish";
var cancelTextFromLang = {
spanish: "Gracias por comunicarte, ¡Adiós!",
english: "Thank you for reaching out, Good bye!",
french: "Merci d'avoir tendu la main, au revoir!"
};
console.log(cancelTextFromLang[language])
You can apply this to your given code like so:
var language = "spanish";
var cancelTextFromLang = {
spanish: "Gracias por comunicarte, ¡Adiós!",
english: "Thank you for reaching out, Good bye!",
french: "Merci d'avoir tendu la main, au revoir!"
};
.cancelAction(
"cancelRequest", cancelTextFromLang[language],
{
matches: /^nevermind$|^cancel$|^cancel.*request/i,
confirmPrompt: "This will cancel your request. Are you sure?"
}
);
Im using session.userData.languagePreference and Im thinking to add an if statement inside the cancelAction but the syntax is wrong, I cant put the if statement there :/
.cancelAction(
if ( session.userData.languagePreference = 0;) {
"cancelRequest", "Thank you for reaching out, Good bye!",
{
matches: /^nevermind$|^cancel$|^cancel.*request/i,
confirmPrompt: "This will cancel your request. Are you sure?"
}
);
The Bot Framework supports localization. You can read about how to do this in Node here. This page will explain how to determine the language for the bot user either via prompting the user or automatically. it also describes how to add the language strings for your prompts.
They key to bot localization is the session.preferredLocal() method. This method saves and gets the user specific locale preference.
The easiest method to determine the language locale and set it is to prompt the user. Here's a Node example
bot.dialog('/localePicker', [
function (session) {
// Prompt the user to select their preferred locale
builder.Prompts.choice(session, "What's your preferred language?", 'English|Español');
},
function (session, results) {
// Update preferred locale
var locale;
switch (results.response.entity) {
case 'English':
locale = 'en';
break;
case 'Español':
locale = 'es';
break;
}
session.preferredLocale(locale, function (err) {
if (!err) {
// Locale files loaded
session.endDialog(`Your preferred language is now ${results.response.entity}`);
} else {
// Problem loading the selected locale
session.error(err);
}
});
}
]);
The first part of this code prompts the user for their preferred language and gives them English and Spanish as the two option available. Based on the user response, the locale code is then set by calling session.preferredLocale().
In order to make use of the user's preferred locale, you will need a corresponding localization prompt file. These files will contain the various bot prompts in the corresponding language. You will need one file per language you intend on supporting.
Normally, these files will be in ./locale/{language}/index.json where {language} is the language code, (ex 'en' or'es'). The files are json and will look like this:
for English
{
"greeting": ["Hello!", "Hi there"]
}
and for Spanish
{
"greeting": ["Hola!", "Hola"]
}
Here is an example of how you code would look
var bot = new builder.UniversalBot(connector, [
function (session) {
session.send("greeting");
session.beginDialog('/localePicker');
},
function (session) {
builder.Prompts.text(session, "text_prompt");
}
]);
Behind the scenes, what's basically happening,the index.json file returned by session.preferredLocale() is searched for the prompt, if it finds one, it returns that otherwise it will return the prompt set for the default locale.

CRM 2013 Javascript get data from another entity based on parameter

I have a situation that is only for users convenience, but is creating a headache for me.
Scenario:
I have (2) custom entities I am concerned with. (1) called "Job" and (1) called "Job Resource." Each have their own form. Job Resource is an N:1 Relationship to a Job.
"Jobs" is just our custom term for an awarded opportunity.
The "Job Resource" is a choice of multiple persons to be associated with that particular job. Those choices are also parameter driven to show "Is Supervisor."
The request I have is to add a "Point of Contact" on the "Job" form, and make it default the "Job Resource, (where 'Is Supervisor'=yes).
I have tried to use Quick View form, but there is no filtered choice for the supervisor or not. I believe I am left to do this with JavaScript. However, I have only done some simple web resources.
I would picture something like:
function xxx_pointOfContactid_onchange() {
xxxToolkit.Common.writeToConsole("begin xxx_pointOfContact_onchange()");
var jobResourceLookup = Xrm.Page.getAttribute("xxx_pointOfContact").getValue();
var select = "xxx_firstname,xxx_lastname,xxx_issupervisor";
if (jobResourceLookup != null) {
xxxToolkit.Rest.Retrieve(
jobResourceLookup[0].id
, "Resource"
, select
, null
, function (retrievedResource) {
if (retrievedResource.issupervisor == 1) {
if (retrievedResource.firstname != null) Xrm.Page.getAttribute("xxx_firstname").setValue(retrievedResource.firstname);
if (retrievedResource.lastname != null) Xrm.Page.getAttribute("xxx_lastname").setValue(retrievedResource.lastname);
} else {
return;
}
, xxxToolkit.Common.errorHandler
, true //asynchronous
);
}
}
When I tried to place this as onChange event, nothing happens.
Again, I am a JavaScript rookie, so if I apologize in advance for rookie question.
Any help appreciated. Thanks so much!

google script - entire form delete

I want to send a form in Email to a group of 15 users. The form would contain just two questions one radial button with a pre-set long code and another one is yes and no. So creating form and emailing the form by doing it within Google Script is NOT the question here.
However, once users submit I want this form to be deleted. I know I can just do isAcceptingResponses() to false and let these old forms dust in my Google Drive. However, if I do that I will keep collecting irrelevant forms in my Google Drive. Is there anyway to destroy a form? or what would you suggest?
Here is an example of creating form as per Google developers manual
https://developers.google.com/apps-script/reference/forms/:
function myCreateForm() {
var form = FormApp.create('Form Autocreaticus');
var item = form.addCheckboxItem();
item.setTitle('What condiments would you like on your hot dog?');
item.setChoices([
item.createChoice('Ketchup'),
item.createChoice('Mustard'),
item.createChoice('Relish')
]);
form.addMultipleChoiceItem()
.setTitle('Do you prefer cats or dogs?')
.setChoiceValues(['Cats','Dogs'])
.showOtherOption(true);
form.addGridItem()
.setTitle('Rate your interests')
.setRows(['Cars', 'Computers', 'Celebrities'])
.setColumns(['Boring', 'So-so', 'Interesting']);
Logger.log('Editor URL: ' + form.getId());
return form.getId() //so I can later use for my myDeleteForm().
}
function myDeleteForm() { //myDeleteForm(formID) {
var formID = '1utQdu9EsuQFgMKNbP5Hjm68fxpP-_vKrBNNXL8jsOZo';
DriveApp.getFileById(formID).setTrashed(true);
}
*This code was changed to accommodate the functionality. Thank you!
To delete the file itself you may need to use the DriveApp. The methods you found only seem to remove/change settings or reponses.
This deletes:
function myDeleteForm() {
var formID = '1utQdu9EsuQFgMKNbP5Hjm68fxpP-_vKrBNNXL8jsOZo';
DriveApp.getFileById(formID).setTrashed(true);
}

How to validate Stock Market data

Honestly, I am not an expert & right now very much confused about how to even state my problem...so please forgive my lack of knowledge and this long confusing question.
I was assigned a project today where the clients are displaying stock market's info on their page (image attached below). And when you click on any one of the buttons (for example, NASDAQ) more info is displayed in a pop-up box.
They are using onClick() to send the whole string to this third party to collect the data. Here is the HTML code for NASDAQ link:
<li>
<a href="#" onClick="open('https://app.quotemedia.com/quotetools/clientForward?symbol=^NASD&targetURL=http://app.quotemedia.com/quotetools/popups/quote.jsp?webmasterId=99944&locale=en_US','miniwin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=550,height=270,top=20,left=0'); return false;">
NASDAQ
<span id="imageNASDAQ"></span>
<span id="valueNASDAQ" class="share_value"></span>
<span id="textNASDAQ"></span>
</a>
<script type="text/javascript" src="/getStockInfo.php?Stocks[NASD]=NASDAQ"></script>
</li>
And then in getStockInfo.php file they are collecting the data as a JSON string and then parsing it. Here's how they are collecting the data:
<?php
if (array_key_exists("Stocks", $_GET)) {
foreach($_GET['Stocks'] as $symbol=>$stock) {
print file_get_contents("https://app.quotemedia.com/quotetools/jsVarsQuotes.go?webmasterId=99944&symbol=$symbol");
?>
So far pretty simple. But now the client wants to do some
"user input validation"
"Only accept 4 symbols: SP500, SPX, DOW & NASDAQ"
This is where I am getting confused. From their code (HTML part) looks like everything is hard coded (open('...symbol=^NASD...'); or open('...symbol=^SPX...'); or open('...symbol=^DJI...');) and each button/link is sending specific Stock symbol's info to the getStockInfo.php file (src="/getStockInfo.php?Stocks[NASD]=NASDAQ" or src="...Stocks[SPX]=SP500" or src="...Stocks[DJI]=DOW") where the stock quotes are being fetched. There is absolutely NO way my client's users can provide any other stock symbols through the site to change the display, the only way to manipulate the symbols are by changing the code itself.
BUT, my client wants to implement these above 2 conditions in the code anyhow. And I am not sure how to do this.
Not sure if I was able to explain my problem properly :( But I really need some help. Also I'm sorry for not being able to provide any link to the actual page here. Thank you so much for reading my confusing post and investing your time!! :)
Here's a proof of concept:
if (array_key_exists("Stocks", $_GET)) {
$stocks = array_filter($_GET['Stocks'], 'filterStocks');
foreach ($stocks as $symbol => $stock) {
print file_get_contents(…);
}
}
function filterStocks($symbol) {
return in_array(
$symbol,
array('SP500', 'SPX', 'DOW', 'NASDAQ')
)
}
Now getStockInfo.php will only return data for the four symbols. If you need that configurable on an individual user basis, a simple solution would be to do change the filterStocks function and callback to
function filterStocksForLoggedInUser($symbol) {
return in_array($symbol, getAllowedSymbolsForUser());
}
function getAllowedSymbolsForUser()
{
$permissions = include '/path/to/permissions/file.php';
return isset($permissions[$_SESSION['username']])
? $permissions[$_SESSION['username']]
: array();
}
}
and then in the permissions file put
return array(
'Walahh' => array('SP500', 'SPX', 'DOW', 'NASDAQ'),
'JohnDoe' => array('SP500', 'GOOG')
);
Note 1: the above assumes you have some sort of way to identify users, here $_SESSION['username']. Change that with whatever you are using and adjust the permission file accordingly.
Note 2: the permissions file will be read each time from disk. Disk I/O is usually slow, so you might want to consider moving the permissions to someplace faster.
Note 3: this is just a proof of concept. It's very pragmatic. You can certainly improve the design and structure, but I guess it's good enough to illustrate how to approach the problem.

Categories

Resources