multiline textfield doesn't work with != as3 - actionscript-3

I wrote some code for some input text fields that need to be filled in before the playhead advances to frame 2.
This is my code:
stop();
var inputText:String;
var inputText2:String;
var inputText3:String;
var inputText4:String;
var inputText5:String;
var inputText6:String;
var inputText7:String;
var inputText8:String;
go.addEventListener(MouseEvent.CLICK, playBtnClickk);
function playBtnClickk(e:MouseEvent):void {
inputText = inputTXT.text;
inputText2 = inputTXT2.text;
inputText3 = inputTXT3.text;
inputText4 = inputTXT4.text;
inputText5 = inputTXT5.text;
inputText6 = inputTXT6.text;
inputText7 = inputTXT7.text;
inputText8 = inputTXT8.text;
if (inputText !== "",
inputText2 !== "",
inputText3 !== "",
inputText4 !== "",
inputText5 !== "",
inputText6 !== "",
inputText7 !== "",
inputText8 !== "")
{ this.setChildIndex(allevelden, this.numChildren - 1); }
else{
gotoAndPlay(2);
}}
But it doesn't work!
If I don't fill in some text this.setChildIndex(allevelden, this.numChildren - 1); - it shows up, but if I fill in all the fields it still shows up and doesn't go to frame 2.
Does someone know how to fix this?

Related

Get Google sheets to updatable JSON script to only need Header row

I have inherited a Google sheet script that generates a Live updatable JSON link from sheets chosen from an HTML form in a sidebar
At the start of a project, the only data that might be present is the Headers on both the Element and Connection sheets (and they are always present) and as the project matures rows of data are added to one or both sheets
My issue is that the script to generate the json requires that at least two rows of data exist (on both sheets) the Header row and a data row
When you run the script you get a pop up with a link then you click that link and a new browser tab opens with the JSON data. It is at this step I get the error
Line 161 in the gs modual is properties.setProperty("settings", newProperties); from
function setExportProperties(newProperties){
var properties = PropertiesService.getDocumentProperties();
var prop = properties.getProperty("settings");
properties.setProperty("settings", newProperties);
}
But this is set on line 292 from the HTML module
function setProperties(){
return google.script.run.setExportProperties(generateProperties());
}
I have tried for hours to figure out how to modify the script so only the header row is necessary but I have not achieved this
There is a lot of code here and it seems to me too much to post it but it is well documented in the code and I think someone who knows what they are doing can figure out pretty easily what needs to be done
From the added menu click Open Sidebar to get to the form. I have set it up in advance
Thank you in advance for your help with this
gs code
//===================================================================================================================
//ExportJson Code
//===================================================================================================================
//Displays an HTML-service dialog in Google Sheets that contains client-side JavaScript code for the Google Picker API.
function showForm() {
var html = HtmlService.createHtmlOutputFromFile('Sidebar.html')
.setTitle('Export Sheet As JSON Data')
.setWidth(300)
.setHeight(480)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showSidebar(html);
}
//function showData(elements,connections,headerrow,datarow,prefix,separator){
function showData(sheets,settings){
//Sheets Array
var elements=sheets[0];
var connections=sheets[1];
//Settings Array
var emptycells=settings[0];
var headerrow=settings[1];
var datarow=settings[2];
var prefix=settings[3];
var separator=settings[4];
var keepignore=settings[5];
var cellarrays=settings[6];
var separator2=settings[7];
var columnignore=settings[8];
var colprefix=settings[9];
var sheetid=SpreadsheetApp.getActiveSpreadsheet().getId();
if(elements=='' && connections==''){
Browser.msgBox('Select any one or both sheets and run again!');
return;
}
if(headerrow=='' || headerrow<=0){
Browser.msgBox('Please enter row number of your data header, it should be an integer value greater than 0');
return;
}
if(datarow=='' || datarow<=0){
Browser.msgBox('Please enter row number where data starts, it should be an integer value greater than 0');
return;
}
if(keepignore==true){
if(prefix=='' && separator!=''){
Browser.msgBox('Please Column Prefix And Array Separator');
return;
}
}
if(columnignore==true){
if(colprefix=='' || colprefix==false){
Browser.msgBox('Please Enter Column Prefix');
return;
}
}
if(cellarrays==true){
if(separator2=='' || separator2==false){
Browser.msgBox('Please Enter Array Separator');
return;
}
}
if(elements=='' && connections==''){
Browser.msgBox('Select sheet(s)!');
return;
}
var webappurl='https://script.google.com/macros/s/AKfycbwn.../exec';
webappurl=webappurl + '?id=' + sheetid;
if(elements!='')
webappurl=webappurl + '&sheet1=' + elements;
else
webappurl=webappurl + '&sheet1=' + '';
if(connections!='')
webappurl=webappurl + '&sheet2=' + connections;
else
webappurl=webappurl + '&sheet2=' + '';
webappurl=webappurl + '&header=' + headerrow;
webappurl=webappurl + '&startrow=' + datarow;
if(keepignore==true){
if(prefix=='' || separator==''){
webappurl=webappurl + '&prefix=' + 'false';
webappurl=webappurl + '&separator=' + 'false';
}
else{
webappurl=webappurl + '&prefix=' + prefix;
webappurl=webappurl + '&separator=' + separator;
}
}
else{
webappurl=webappurl + '&prefix=' + 'false';
webappurl=webappurl + '&separator=' + 'false';
}
if(emptycells==true)
webappurl=webappurl + '&emptycells=' + 'yes';
else
webappurl=webappurl + '&emptycells=' + 'no';
if(cellarrays==true){
webappurl=webappurl + '&cellarrays=' + 'yes';
webappurl=webappurl + '&separator2=' + separator2;
}
else{
webappurl=webappurl + '&cellarrays=' + 'no';
webappurl=webappurl + '&separator2=' + 'no';
}
if(columnignore==true){
webappurl=webappurl + '&columnignore=' + 'yes';
webappurl=webappurl + '&colprefix=' + colprefix;
}
else{
webappurl=webappurl + '&columnignore=' + 'no';
webappurl=webappurl + '&colprefix=' + 'no';
}
//Workflows.setCurrentMapSource("");
var kumuurl='Workflows.setCurrentMapSource("'+ webappurl +'")';
openUrl(webappurl,kumuurl);
}
//===================================================================================================================
function openUrl( url,kumuurl ){
var html = HtmlService.createHtmlOutput('<html>'
//+'<script>'
//+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
//+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
//+'if(document.createEvent){'
//+' var event=document.createEvent("MouseEvents");'
//+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
//+' event.initEvent("click",true,true); a.dispatchEvent(event);'
//+'}else{ a.click() }'
//+'close();'
//+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">' + kumuurl + '</body>'
+'<script>google.script.host.setHeight(150);google.script.host.setWidth(600)</script>'
+'</html>')
.setWidth(600).setHeight(1);
SpreadsheetApp.getUi().showModalDialog( html, "Click the Link below to get the LIVE Link" );
}
//===================================================================================================================
function setExportProperties(newProperties){
var properties = PropertiesService.getDocumentProperties();
var prop = properties.getProperty("settings");
properties.setProperty("settings", newProperties);
}
//===================================================================================================================
function getExportProperties(){
var props = PropertiesService.getDocumentProperties();
var prop = props.getProperty("settings");
//Logger.log(prop);
return prop;
}
//===================================================================================================================
function getSheetList(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheets=ss.getSheets();
var sheetnames=[];
sheetnames[0]="|"
for(var i=0;i<sheets.length;i++){
var sh=sheets[i];
sheetnames[i+1]=sh.getName()+"|"+sh.getName();
}
return sheetnames;
}
//===================================================================================================================
//LiveJson Code
//===================================================================================================================
function doGet(request) {
// Get request params.
var sheetKey = request.parameters.id;
var sheetName1 = request.parameters.sheet1;
var sheetName2 = request.parameters.sheet2;
var callback = request.parameters.callback;
var headerRow = request.parameters.header;
var startRow = request.parameters.startrow;
var prefix = request.parameters.prefix;
var separator = request.parameters.separator;
var emptycells = request.parameters.emptycells;
var cellarrays = request.parameters.cellarrays;
var separator2 = request.parameters.separator2;
var columnignore = request.parameters.columnignore;
var colprefix = request.parameters.colprefix;
// Parse the spreadsheet.
var spreadsheet = SpreadsheetApp.openById(sheetKey); //.getActiveSpreadsheet();
if(sheetName1!=''){
var keys = getHeaderRowKeys_(spreadsheet, sheetName1, headerRow, columnignore, colprefix);
var data1 = readData_(spreadsheet, sheetName1, headerRow, keys, startRow,prefix,separator,emptycells,cellarrays,separator2,columnignore, colprefix);
}
if(sheetName2!=''){
var keys = getHeaderRowKeys_(spreadsheet, sheetName2, headerRow, columnignore, colprefix);
var data2 = readData_(spreadsheet, sheetName2,headerRow, keys, startRow,prefix,separator,emptycells,cellarrays,separator2,columnignore, colprefix);
}
// Write and return the response.
if(sheetName1!='' && sheetName2!=''){
var response = JSON.stringify({ elements: data1,connections: data2 },null,'\t');
}
else if(sheetName1!='' && sheetName2==''){
var response = JSON.stringify({ elements: data1 },null,'\t');
}
else if(sheetName1=='' && sheetName2!=''){
var response = JSON.stringify({ connections: data2 },null,'\t');
}
var output = ContentService.createTextOutput();
if(callback == undefined){
// Serve as JSON
output.setContent(response).setMimeType(ContentService.MimeType.JSON);
}
else{
// Serve as JSONP
output.setContent(callback + "(" + response + ")").setMimeType(ContentService.MimeType.JAVASCRIPT);
}
//output.setContent(callback + "(" + response + ")").setMimeType(ContentService.MimeType.JAVASCRIPT);
return output;
}
//===================================================================================================================
function readData_(spreadsheet, sheetName, headerRow, properties, startRowNum, prefix,separator,emptycells,cellarrays,separator2,columnignore, colprefix) {
if (typeof properties == "undefined") {
properties = getHeaderRowKeys_(spreadsheet, sheetName, headerRow, columnignore, colprefix);
}
var rows = getDataRows_(spreadsheet, sheetName,headerRow, startRowNum,columnignore, colprefix);
var data = [];
if(emptycells=='yes'){//Ignore Empty Cells
for (var i = 0; i<rows.length; i++) {
var row = rows[i];
var record = {};
for (var p in properties) {
if(row[p]!=''){
var keys=properties
record=updateRecord(prefix,keys,p,row,record,prefix,separator,cellarrays,separator2)
//properties[p]=properties[p].replace(prefix,"")
}
}
data.push(record);
}
}
else{//Inclue Empty Cells
for (var i = 0; i<rows.length; i++) {
var row = rows[i];
var record = {};
for (var p in properties) {
var keys=properties
record=updateRecord(prefix,keys,p,row,record,prefix,separator,cellarrays,separator2)
}
data.push(record);
}
}
return data;
}
//===================================================================================================================
function updateRecord(prefix,properties,p,row,record,prefix,separator,cellarrays,separator2){
if(prefix=='false'){
if(cellarrays=='yes'){//Split Cell Values as arrays if contains comma
if(row[p].toString().indexOf(separator2)>=0){//Convert Cell As Array Only If Contains Comma
record[properties[p]]=row[p].toString().split(separator2);
}
else{
record[properties[p]]=row[p];
}
}
else{
record[properties[p]]=row[p];
}
}
else{//Split Entire Column as array if start with a prefix
var key=properties[p];
if(key.indexOf(prefix)==0){
key=key.replace(prefix,"")
if(row[p].toString().indexOf(separator)>=0)
record[key]=row[p].toString().split(separator);
else if(row[p].toString().indexOf(separator2)>=0)
if(cellarrays='yes')
record[key]=row[p].toString().split(separator2);
else
record[key]=row[p];
else
record[key]=row[p];
}
else{
if(cellarrays=='yes'){//Split Cell Values as arrays if contains separator2
if(row[p].toString().indexOf(separator2)>=0){//Convert Cell As Array Only If Contains separator2
record[key]=row[p].toString().split(separator2);
}
else{
record[key]=row[p];
}
}
else{
record[key]=row[p];
}
}
}
return record;
}
//===================================================================================================================
function getDataRows_(spreadsheet, sheetName, headerRow, startRowNum, columnignore, colprefix) {
var properties = getHeaderRow_2(spreadsheet, sheetName, headerRow, columnignore, colprefix);
if (typeof startRowNum == "undefined") startRowNum = 2;
var sheet = spreadsheet.getSheetByName(sheetName);
var values=sheet.getRange(startRowNum, 1, sheet.getLastRow()-1, sheet.getLastColumn()).getValues();
if(columnignore=='yes'){
var data=[];
for(var i=0;i<values.length;i++){
data[i]=[];
var k=0;
for(var j=0;j<properties.length;j++){
if(properties[j].toString().indexOf(colprefix)!=0){
data[i][k]=values[i][j];
k++;
}
}
}
return data;
}
else
return values;
}
//======================================================================================================================================================================================
function getHeaderRowKeys_(spreadsheet, sheetName, rowNum, columnignore, colprefix) {
if (typeof rowNum == "undefined") rowNum = 1;
var header=getHeaderRow_(spreadsheet, sheetName, rowNum, columnignore, colprefix);
return header;
}
//===================================================================================================================
function getHeaderRow_(spreadsheet, sheetName, rowNum, columnignore, colprefix) {
var sheet = spreadsheet.getSheetByName(sheetName);
var values=sheet.getRange(rowNum, 1, 1, sheet.getLastColumn()).getValues();
if(columnignore=='yes'){
var data=[];
for(var i=0;i<values.length;i++){
data[i]=[];
var k=0;
for(var j=0;j<values[0].length;j++){
if(values[i][j].toString().indexOf(colprefix)!=0){
data[i][k]=values[i][j];
k++;
}
}
}
return data[0];
}
else
return values[0];
}
//===================================================================================================================
function getHeaderRow_2(spreadsheet, sheetName, rowNum, columnignore, colprefix) {
var sheet = spreadsheet.getSheetByName(sheetName);
var values=sheet.getRange(rowNum, 1, 1, sheet.getLastColumn()).getValues();
return values[0];
}
HTML code (some CSS remove so as not to exceed char limit)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<base target="_top">
</head>
<body>
<body onload="populate()"></body>
<div class="main">
<h2 align="center" style="font-family:Open+Sans;"> Select Sheets</h2>
<div class="section">
<div class="block form-group">
<br>
<center> <label for="elmn">Select Elements Sheet</label>
<select id="elmn" name="elmn" style="width: 180px;" ></select>
<br>
<label for="conn">Select Connections Sheet</label>
<select id="conn" name="conn" style="width: 180px;" ></select></center>
</div>
</div>
<h2 align="center" style="font-family:Open+Sans;">General Data</h2>
<div class="section">
<div id="new-div">
<center>Header Row:<br>
<input type="text" name="Header Row" value="1" id="headerrow">
<br><br>
Start Data Row:<br>
<input type="text" name="Data Row" value="2" id="datarow"> </center>
</div>
</div>
<h2 align="center" style="font-family:Open+Sans;">JSON Settings</h2>
<div class="buttonDiv" >
<!--<div class="newButtonDiv"></div>-->
<button class="action" value="Run" onclick="get_form_values()">View</button>
<input type="reset" value="Reset" onclick="enableTextBox()">
</div>
</div>
<script>
var elements = "";
var connections = "";
var emptycells = "";
var headerrow = "";
var datarow = "";
var prefix = "";
var separator = "";
var keepignore = "";
var cellarrays = "";
var separator2 = "";
var columnignore="";
var colprefix="";
var elementsIndex = "";
var elementsValue = "";
var connectionsIndex = "";
var connectionsValue = "";
function populate(){
var elementlist=document.getElementById('elmn');
var connectlist=document.getElementById('conn');
//document.getElementById("elmn").innerHTML = "";
//document.getElementById("conn").innerHTML = "";
function onSuccess(optionarray) {
for(var option in optionarray){
var pair=optionarray[option].split("|")
var newoption=document.createElement("Option");
newoption.value=pair[0];
newoption.innerHTML=pair[1];
elementlist.options.add(newoption);
var newoption=document.createElement("Option");
newoption.value=pair[0];
newoption.innerHTML=pair[1];
connectlist.options.add(newoption);
}
elementlist.selectedIndex=elementsIndex;
connectlist.selectedIndex=connectionsIndex;
}
//console.log(document.getElementById('elmn').options);
google.script.run.withSuccessHandler(onSuccess).getSheetList();
enableTextBox();
}
function get_form_values(){
//...
var e = document.getElementById('elmn');
elementsValue = e.options[e.selectedIndex].value;
elements = e.options[e.selectedIndex].text;
elementsIndex = e.options[e.selectedIndex].index;
//...
//...
var c = document.getElementById('conn');
connectionsValue = c.options[c.selectedIndex].value;
connections = c.options[c.selectedIndex].text;
connectionsIndex = c.options[c.selectedIndex].index;
//...
emptycells=document.getElementById('emptycells').checked;
headerrow=document.getElementById('headerrow').value;
datarow=document.getElementById('datarow').value;
prefix=document.getElementById('prefix').value;
separator=document.getElementById('separator').value;
keepignore=document.getElementById('keepignore').checked;
cellarrays=document.getElementById('cellarrays').checked;
separator2=document.getElementById('separator2').value;
columnignore=document.getElementById('columnignore').checked;
colprefix=document.getElementById('colprefix').value;
var sheets=[];
sheets[0]=elements;
sheets[1]=connections;
var settings=[];
settings[0]=emptycells;
settings[1]=headerrow;
settings[2]=datarow;
settings[3]=prefix;
settings[4]=separator;
settings[5]=keepignore;
settings[6]=cellarrays;
settings[7]=separator2;
settings[8]=columnignore;
settings[9]=colprefix;
setProperties();
google.script.run.showData(sheets,settings);
}
function setProperties(){
return google.script.run.setExportProperties(generateProperties());
}
function generateProperties(){
var properties = {
//General settings
"emptycells" : emptycells,
"headerrow" : headerrow,
"datarow" : datarow,
"prefix" : prefix,
"separator" : separator,
"keepignore" : keepignore,
"cellarrays" : cellarrays,
"columnignore" : columnignore,
"colprefix" : colprefix,
"separator2" : separator2,
"elements" : elements,
"connections" : connections,
"elementsIndex" : elementsIndex,
"elementsValue": elementsValue,
"connectionsIndex" : connectionsIndex,
"connectionsValue": connectionsValue,
};
return JSON.stringify(properties);
}
//Actually sets the local properties based on stored settings.
function updateProperties(properties){
var settings;
if(properties == null || properties === ""){
settings = {};
}
else{
settings = JSON.parse(properties);
}
//General
//connections = settings["connections"] != null ? settings["connections"] : connections;
elements = settings["elements"] != null ? (settings["elements"] === "" ? elements : settings["elements"]) : elements
elementsIndex = settings["elementsIndex"] != null ? settings["elementsIndex"] : elementsIndex;
elementsValue = settings["elementsValue"] != null ? settings["elementsValue"] : elementsValue;
connections = settings["connections"] != null ? (settings["connections"] === "" ? connections : settings["connections"]) : connections
connectionsIndex = settings["connectionsIndex"] != null ? settings["connectionsIndex"] : connectionsIndex;
connectionsValue = settings["connectionsValue"] != null ? settings["connectionsValue"] : connectionsValue;
emptycells = settings["emptycells"] != null ? settings["emptycells"] : emptycells;
headerrow = settings["headerrow"] != null ? settings["headerrow"] : headerrow;
datarow = settings["datarow"] != null ? settings["datarow"] : datarow;
prefix = settings["prefix"] != null ? settings["prefix"] : prefix;
separator = settings["separator"] != null ? settings["separator"] : separator;
keepignore = settings["keepignore"] != null ? settings["keepignore"] : keepignore;
cellarrays = settings["cellarrays"] != null ? settings["cellarrays"] : cellarrays;
separator2 = settings["separator2"] != null ? settings["separator2"] : separator2;
columnignore = settings["columnignore"] != null ? settings["columnignore"] : columnignore;
colprefix = settings["colprefix"] != null ? settings["colprefix"] : colprefix;
refreshSideBar();
//populate(elementsValue, connectionsValue);
}
//Function to rebuild the sidebar after loading export parameters
function refreshSideBar(){
document.getElementById('emptycells').checked=emptycells;
if(headerrow=="")
document.getElementById('headerrow').value="1";
else
document.getElementById('headerrow').value=headerrow;
if(datarow=="")
document.getElementById('datarow').value="2";
else
document.getElementById('datarow').value=datarow;
if(prefix=="")
document.getElementById('prefix').value="ja_";
else
document.getElementById('prefix').value=prefix;
if(separator=="")
document.getElementById('separator').value="|";
else
document.getElementById('separator').value=separator;
document.getElementById('keepignore').checked=keepignore;
document.getElementById('cellarrays').checked=cellarrays;
document.getElementById('columnignore').checked=columnignore;
if(colprefix=="")
document.getElementById('colprefix').value="ig_";
else
document.getElementById('colprefix').value=colprefix;
if(separator2=="")
document.getElementById('separator2').value="|";
else
document.getElementById('separator2').value=separator2;
EnableTextbox1('keepignore', 'prefix' ,'separator')
EnableTextbox('columnignore', 'colprefix')
EnableTextbox('cellarrays', 'separator2')
}
function getProperties(onSuccess){
return google.script.run.withSuccessHandler(onSuccess).getExportProperties();
}
//enable disable
function EnableTextbox(CheckboxId,TextboxId1){
if(document.getElementById(CheckboxId).checked){
document.getElementById(TextboxId1).style.backgroundColor = "#fff"
document.getElementById(TextboxId1).disabled=false;
}
else{
document.getElementById(TextboxId1).style.backgroundColor = "#5bb800"
document.getElementById(TextboxId1).disabled=true;
}
}
function EnableTextbox1(CheckboxId,TextboxId1, TextboxId2){
if(document.getElementById(CheckboxId).checked){
document.getElementById(TextboxId1).style.backgroundColor = "#fff";
document.getElementById(TextboxId2).style.backgroundColor = "#fff";
document.getElementById(TextboxId1).disabled=false;
document.getElementById(TextboxId2).disabled=false;
}
else{
document.getElementById(TextboxId1).style.backgroundColor = "#5bb800";
document.getElementById(TextboxId2).style.backgroundColor = "#5bb800";
document.getElementById(TextboxId1).disabled=true;
document.getElementById(TextboxId2).disabled=true;
}
}
function enableTextBox(){
document.getElementById("elmn").selectedIndex = 0;
document.getElementById("conn").selectedIndex = 0;
document.getElementById("headerrow").value = "1";
document.getElementById("datarow").value = "2";
document.getElementById("emptycells").checked = false;
//========================================================
document.getElementById("keepignore").checked = false;
document.getElementById("prefix").value = "ja_";
document.getElementById("separator").value = "|";
document.getElementById("columnignore").checked = false;
document.getElementById("colprefix").value = "ig_";
document.getElementById("cellarrays").checked = false;
document.getElementById("separator2").value = "|";
document.getElementById("prefix").style.backgroundColor = "#5bb800";
document.getElementById("separator").style.backgroundColor = "#5bb800";
document.getElementById("colprefix").style.backgroundColor = "#5bb800";
document.getElementById("separator2").style.backgroundColor = "#5bb800";
document.getElementById("prefix").disabled=true;
document.getElementById("separator").disabled=true;
document.getElementById("colprefix").disabled=true;
document.getElementById("separator2").disabled=true;
}
//end
getProperties(updateProperties);
</script>
</body>
</html>
I believe your goal is as follows.
You want to remove the following error. (The following image is from your question.)
When I saw your script and your sample Spreadsheet, I noticed that your sheet of "Connections" has only the header row. In this case, an error occurs at var values=sheet.getRange(startRowNum, 1, sheet.getLastRow()-1, sheet.getLastColumn()).getValues(); in your script. Because sheet.getLastRow()-1 is 0. So, in your situation, how about the following modification?
From:
var values=sheet.getRange(startRowNum, 1, sheet.getLastRow()-1, sheet.getLastColumn()).getValues();
To:
var rows = sheet.getLastRow() - 1;
var values = rows > 0 ? sheet.getRange(startRowNum, 1, rows, sheet.getLastColumn()).getValues() : [];
By this modification, when "Connections" sheet has only the header, [] is used as values.

"Invalid Argument" error with addLabel(label) method

For a while now, I've been trying to create an autolabeler for Gmail in Google Apps Script. This script parses through an email's body and looks for a line with the form "#DL:", extracts the text after that (which is a date), runs this string through a standardizer I have coded, calculates the date difference between that date and now, and if it's urgent, assigns a color to that. It gets all that information and labels that email. Here is the code I use:
var filters = [{
match: /[\n\r][ \t]*#DL:[ \t]*([^\n\r]*)/,
archive: false
}, ];
var from = [];
function labeler() {
var batchSize = 10;
var labelCache = {};
var query = "in:anywhere";
var threads = GmailApp.search(query, 0, batchSize);
GmailApp.getMessagesForThreads(threads);
var findOrCreateLabel = function(name) {
if (labelCache[name] === undefined) {
labelCache[name] = GmailApp.getUserLabelByName(name) || createLabelByGmailApi(name);
}
//GmailApp.createLabel(name);
//createLabelByGmailApi(name);
return labelCache[name];
}
var applyLabel = function(name, thread) {
var label = null;
var labelName = "";
name.split('&').forEach(function(labelPart, i) {
labelName = labelName + (i === 0 ? "" : "&") + labelPart.trim();
label = findOrCreateLabel(labelName);
});
thread.addLabel(label);
}
threads.forEach(function(thread) {
var messages = thread.getMessages();
if (messages == null) return;
var message = messages[messages.length - 1];
var body = message.getRawContent();
var archive = true;
filters.forEach(function(filter) {
var matches = filter.match.exec(body);
if (matches !== null) {
var label = filter.name || matches[1];
var data = datestd(label);
var cor = datecalc(data);
label = "Datas/" + data;
if (label !== undefined) applyLabel(label, thread);
if (filter.archive !== undefined && !filter.archive) archive = false;
}
});
if (archive) thread.moveToArchive();
});
}
function createLabelByGmailApi(name, color) {
var label = GmailApp.getUserLabelByName(name);
if (label) return label;
var textColor = "#ffffff";
if (color == 'red') {
var backgroundColor = "#ac2b16";
} else if (color == 'yellow') {
var backgroundColor = "#fad165";
} else if (color == 'green') {
var backgroundColor = "#076239";
} else {
var backgroundColor = "#41236d";
}
var userId = "me";
var resource = Gmail.newLabel();
resource.labelListVisibility = "labelShow";
resource.messageListVisibility = "show";
resource.name = name;
var labelColor = Gmail.newLabelColor();
labelColor.textColor = textColor;
labelColor.backgroundColor = backgroundColor;
resource.color = labelColor;
Gmail.Users.Labels.create(resource, userId);
return GmailApp.getUserLabelByName(name);
}
function datecalc(stringdata) {
var len = stringdata.length
var min = stringdata.slice(len - 2, len);
var hora = stringdata.slice(len - 5, len - 3);
var mes = stringdata.slice(len - 9, len - 7);
var dia = stringdata.slice(len - 12, len - 10);
min = Number(min);
hora = Number(hora);
mes = Number(mes);
dia = Number(dia);
var data = new Date(2019, mes - 1, dia, hora, min);
var data2 = Date.now();
var diff = data - data2;
diff = diff / 86400000
var color;
if (diff <= 1.5) {
color = 'red'
} else if (diff > 1.5 && diff <= 4) {
color = 'yellow'
} else {
color = 'green'
}
return color;
}
function mesnum(mon) {
var m = {
'jan': '01',
'fev': '02',
'mar': '03',
'abr': '04',
'mai': '05',
'jun': '06',
'jul': '07',
'ago': '08',
'set': '09',
'out': '10',
'nov': '11',
'dez': '12'
};
var s = mon.slice(0, 3)
var idc = String(m[s]);
if (idc.length < 2) {
idc = "0" + idc;
}
return idc;
}
function datestd(date) {
var ano = "2019";
var whitelistdias = ["terça-feira", "quarta-feira",
"quinta-feira", "sexta-feira", "sábado", "domingo",
"segunda", "terça", "quarta", "quinta", "sexta", "sabado",
"terca"
];
var whitelistmes = ["janeiro", "fevereiro", "março", "abril", "maio", "junho",
"julho", "agosto", "setembro", "outubro", "novembro",
"dezembro", "jan", "fev", "mar", "abr", "mai", "jun",
"jul", "ago", "set", "out", "nov", "dez"
];
var whitelistchar = ["/", "-", "."];
var idk = date.toLowerCase();
idk = idk.replace(/,/g, " ,");
idk = idk.split(" ");
var v;
var pos;
var dia;
var hora;
var mes;
var searchd;
var posfinal;
if (whitelistmes.some(function(v) {
return idk.indexOf(v) !== -1;
}) == true) {
idk = String(idk);
whitelistmes.forEach(function(strs) {
return idk.replace(strs, "");
});
whitelistdias.forEach(function(strq) {
return idk.replace(strq, "");
});
idk = String(idk);
idk = idk.replace("[", "");
idk = idk.replace(".", ":");
idk = idk.replace("]", "");
idk = idk.replace("de", "");
idk = idk.replace(" ", "");
idk = idk.replace("'", "");
idk = idk.replace("as", ",");
idk = idk.replace("at", ",");
idk = idk.replace("of", ",");
idk = idk.replace("às", ",");
idk = idk.replace("h", "");
idk = idk.replace(ano, "");
pos = idk.indexOf(",");
dia = idk.slice(0, pos);
idk = String(idk);
hora = idk.slice(idk.lastIndexOf(",") + 1, idk.length);
idk = idk.split(",");
mes = idk.filter(function(n) {
return whitelistmes.indexOf(n) !== -1;
});
mes = String(mes);
return dia + "/" + mesnum(mes) + ", " + hora;
} else {
idk = String(idk);
if (idk.includes("/") || idk.includes("-")) {
whitelistmes.forEach(function(strs) {
return idk.replace(strs, "");
});
whitelistdias.forEach(function(strq) {
return idk.replace(strq, "");
});
}
idk = String(idk);
idk = idk.replace(".", ":");
idk = idk.replace("[", "");
idk = idk.replace("]", "");
idk = idk.replace("de", "");
idk = idk.replace(/ /g, "");
idk = idk.replace("'", "");
idk = idk.replace("as", ",");
idk = idk.replace("às", ",");
idk = idk.replace(ano, "");
var hmm = new Array();
idk = idk.split('');
hmm = idk.reduce(function(matches, character, index) {
if (whitelistchar.includes(character)) hmm.push(index);
return hmm;
}, []);
hmm = String(hmm);
hmm = hmm.replace("[", "");
hmm = hmm.replace("]", "");
hmm = hmm.replace(" ", "");
var pos1 = hmm.indexOf(",");
if (pos1 !== -1) {
var prim = hmm.slice(0, pos1);
prim = Number(prim);
var seg = hmm.slice(pos1 + 1, hmm.length);
seg = Number(seg);
dia = idk.slice(0, prim);
mes = idk.slice(prim + 1, seg);
hora = idk.slice(seg + 1, idk.length);
} else {
hmm = Number(hmm);
pos1 = idk.indexOf(",");
dia = idk.slice(0, hmm);
mes = idk.slice(hmm + 1, pos1);
hora = idk.slice(pos1 + 1, idk.length);
}
hora = String(hora);
searchd = hora.match(/\d/);
posfinal = hora.indexOf(searchd);
hora = hora.slice(posfinal, hora.length);
idk = String(idk);
idk = idk.replace(/,/g, "");
dia = String(dia);
mes = String(mes);
hora = String(hora);
dia = dia.replace(/,/g, "");
mes = mes.replace(/,/g, "");
hora = hora.replace(/,/g, "");
hora = hora.replace(/h/g, "");
return dia + "/" + mes + ", " + hora;
}
}
To give some context to what's happening:
The labeler function gets the string from the email, sends it to the datestd function to get standardized, and that output is the name of the label. That output is also used to calculate the date difference between that date and now, through the function datecalc, which outputs a color. This color will be used by the createLabelByGmailApi function to create a label with that name and color. After this, the labeler function applies that label to the email in question.
There are 2 problems I am trying to fix, to no avail:
1. Invalid Argument Error
When running the code above, I get an "Invalid Argument" error in the thread.addLabel(label); line (the argument is label), and I don't know why.
2. Can't seem to fetch the color for the createLabelByGmailApi function
Due to the way the code is structured, I can't seem to fetch the color for the function, since this color depends on the date, which depends on the parsing of the email body, which happens later in the function. I can't seem to find a way to rearrange this so I am able to provide a color for the function, would be great if you could help.
I know this is a handful, and thanks so much for reading this, your help would be much appreciated.
How about this modification?
It seems that the reason of your issue is the crated label is not reflected soon when Gmail.Users.Labels.create() is run. By this, label became null. In order to remove this issue, I added the label using Gmail.Users.Threads.modify() when the label was created with Gmail.Users.Labels.create(). Please modify as follows.
Modified script:
Please modify applyLabel() of labeler() as follows.
From:
var applyLabel = function(name, thread) {
var label = null;
var labelName = "";
name.split('&').forEach(function(labelPart, i) {
labelName = labelName + (i === 0 ? "" : "&") + labelPart.trim();
label = findOrCreateLabel(labelName);
});
thread.addLabel(label);
}
To:
var applyLabel = function(name, thread) {
var label = null;
var labelName = "";
name.split('&').forEach(function(labelPart, i) {
labelName = labelName + (i === 0 ? "" : "&") + labelPart.trim();
label = findOrCreateLabel(labelName);
});
if (typeof label == "string") {
Gmail.Users.Threads.modify({addLabelIds: [label]}, "me", thread.getId());
} else {
thread.addLabel(label);
}
}
And, please modify createLabelByGmailApi() as follows.
From:
Gmail.Users.Labels.create(resource, userId);
return GmailApp.getUserLabelByName(name);
To:
return Gmail.Users.Labels.create(resource, userId).id;
Note:
At labelCache[name] = GmailApp.getUserLabelByName(name) || createLabelByGmailApi(name);, when createLabelByGmailApi(name) is called, name is used as the argument. But at the function of createLabelByGmailApi(name, color), name and color are used as the arguments. I think that in the current situation, #41236d is used as the default value. Please confirm this.
When I see the function of datestd(), I noticed that includes() is used. In the current stage, it cannot be used for Google Apps Script. So includes() is declared at elsewhere?
If I misunderstood your situation and this was not the direction you want, I apologize.

checking if textfield is empty with multiline doesn''t work as3

this is my code:
stop();
var inputText:String;
var inputText2:String;
var inputText3:String;
var inputText4:String;
var inputText5:String;
var inputText6:String;
var inputText7:String;
var inputText8:String;
go.addEventListener(MouseEvent.CLICK, playBtnClickk);
function playBtnClickk(e:MouseEvent):void {
inputText = inputTXT.text;
inputText2 = inputTXT2.text;
inputText3 = inputTXT3.text;
inputText4 = inputTXT4.text;
inputText5 = inputTXT5.text;
inputText6 = inputTXT6.text;
inputText7 = inputTXT7.text;
inputText8 = inputTXT8.text;
if (
inputText2 !== "",
inputText3 !== "",
inputText4 !== "",
inputText5 !== "",
inputText6 !== "",
inputText7 !== "",
inputText8 !== "")
{ this.setChildIndex(allevelden, this.numChildren - 1); }
else{
gotoAndPlay(2);
}}
I one field isn't filled in, this.setChildIndex(allevelden, this.numChildren - 1); has to shop up, and if everything is filled in it has to go to frame 2.
all the textfields are input textfields and multilines but it doesn't work can someone help me please!!
I might be wrong but I never saw this syntax of separaring the condition on the if statement with a comma, you should separate your condintions with a double pipe for or, also your check is incorrect, try this:
if (
inputText == "" ||
inputText2 == "" ||
inputText3 == "" ||
inputText4 == "" ||
inputText5 == "" ||
inputText6 == "" ||
inputText7 == "" ||
inputText8 == "")
{ this.setChildIndex(allevelden, this.numChildren - 1); }
else{
gotoAndPlay(2);
}}
This reads: If any of your fields is empty then...

Change keyboard button effects on HTML

Whilst in a html textarea input, I want the tab keyboard button to act like a Word processor-style indentation key rather than skipping to the next element.
How can this be done?
google is your friend! link
function insertTab(o, e)
{
var kC = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which;
if (kC == 9 && !e.shiftKey && !e.ctrlKey && !e.altKey)
{
var oS = o.scrollTop;
if (o.setSelectionRange)
{
var sS = o.selectionStart;
var sE = o.selectionEnd;
o.value = o.value.substring(0, sS) + "\t" + o.value.substr(sE);
o.setSelectionRange(sS + 1, sS + 1);
o.focus();
}
else if (o.createTextRange)
{
document.selection.createRange().text = "\t";
e.returnValue = false;
}
o.scrollTop = oS;
if (e.preventDefault)
{
e.preventDefault();
}
return false;
}
return true;
}
<textarea onkeydown="insertTab(this, event);"></textarea>

jquery cookies for different countries link

I am trying to do cookie stuff in jquery
but it not getting implemented can you guys fix my problem
html code
<a rel="en_CA" class="selectorCountries marginUnitedStates locale-link" href="http://www.teslamotors.com/en_CA">united states</a>
<a rel="en_US" class="selectorCountries marginSecondCountry locale-link" href="http://www.teslamotors.com/en_CA">canada</a>
<a rel="en_BE" class="selectorCountries marginCanadaFrench locale-link" href="http://www.teslamotors.com/en_BE">canada(french)</a>
i am providing my js code below
http://jsfiddle.net/SSMX4/76/
when i click the different country links in the pop up it should act similar to this site
http://www.teslamotors.com/it_CH
$('.locale-link').click(function(){
var desired_locale = $(this).attr('rel');
createCookie('desired-locale',desired_locale,360);
createCookie('buy_flow_locale',desired_locale,360);
closeSelector('disappear');
})
$('#locale_pop a.close').click(function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',3,360);
}
else if (show_blip_count < 3 ) {
eraseCookie('show_blip_count');
createCookie('show_blip_count',3,360);
}
$('#locale_pop').slideUp();
return false;
});
function checkCookie(){
var cookie_locale = readCookie('desired-locale');
var show_blip_count = readCookie('show_blip_count');
var tesla_locale = 'en_US'; //default to US
var path = window.location.pathname;
// debug.log("path = " + path);
var parsed_url = parseURL(window.location.href);
var path_array = parsed_url.segments;
var path_length = path_array.length
var locale_path_index = -1;
var locale_in_path = false;
var locales = ['en_AT', 'en_AU', 'en_BE', 'en_CA',
'en_CH', 'de_DE', 'en_DK', 'en_GB',
'en_HK', 'en_EU', 'jp', 'nl_NL',
'en_US', 'it_IT', 'fr_FR', 'no_NO']
// see if we are on a locale path
$.each(locales, function(index, value){
locale_path_index = $.inArray(value, path_array);
if (locale_path_index != -1) {
tesla_locale = value == 'jp' ? 'ja_JP':value;
locale_in_path = true;
}
});
// debug.log('tesla_locale = ' + tesla_locale);
cookie_locale = (cookie_locale == null || cookie_locale == 'null') ? false:cookie_locale;
// Only do the js redirect on the static homepage.
if ((path_length == 1) && (locale_in_path || path == '/')) {
debug.log("path in redirect section = " + path);
if (cookie_locale && (cookie_locale != tesla_locale)) {
// debug.log('Redirecting to cookie_locale...');
var path_base = '';
switch (cookie_locale){
case 'en_US':
path_base = path_length > 1 ? path_base:'/';
break;
case 'ja_JP':
path_base = '/jp'
break;
default:
path_base = '/' + cookie_locale;
}
path_array = locale_in_path != -1 ? path_array.slice(locale_in_path):path_array;
path_array.unshift(path_base);
window.location.href = path_array.join('/');
}
}
// only do the ajax call if we don't have a cookie
if (!cookie_locale) {
// debug.log('doing the cookie check for locale...')
cookie_locale = 'null';
var get_data = {cookie:cookie_locale, page:path, t_locale:tesla_locale};
var query_country_string = parsed_url.query != '' ? parsed_url.query.split('='):false;
var query_country = query_country_string ? (query_country_string.slice(0,1) == '?country' ? query_country_string.slice(-1):false):false;
if (query_country) {
get_data.query_country = query_country;
}
$.ajax({
url:'/check_locale',
data:get_data,
cache: false,
dataType: "json",
success: function(data){
var ip_locale = data.locale;
var market = data.market;
var new_locale_link = $('#locale_pop #locale_link');
if (data.show_blip && show_blip_count < 3) {
setTimeout(function(){
$('#locale_msg').text(data.locale_msg);
$('#locale_welcome').text(data.locale_welcome);
new_locale_link[0].href = data.new_path;
new_locale_link.text(data.locale_link);
new_locale_link.attr('rel', data.locale);
if (!new_locale_link.hasClass(data.locale)) {
new_locale_link.addClass(data.locale);
}
$('#locale_pop').slideDown('slow', function(){
var hide_blip = setTimeout(function(){
$('#locale_pop').slideUp('slow', function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',1,360);
}
else if (show_blip_count < 3 ) {
var b_count = show_blip_count;
b_count ++;
eraseCookie('show_blip_count');
createCookie('show_blip_count',b_count,360);
}
});
},10000);
$('#locale_pop').hover(function(){
clearTimeout(hide_blip);
},function(){
setTimeout(function(){$('#locale_pop').slideUp();},10000);
});
});
},1000);
}
}
});
}
This will help you ALOT!
jQuery Cookie Plugin
I use this all the time. Very simple to learn. Has all the necessary cookie functions built-in and allows you to use a tiny amount of code to create your cookies, delete them, make them expire, etc.
Let me know if you have any questions on how to use (although the DOCS have a decent amount of instruction).