Else If - Google Script - if-statement

this script was working before on my Google Sheet, then all of a sudden, it stopped working. I notice that the first argument (if) is working, but all the codes after that is not working. Any ideas?
function onEdit(event) {
// assumes source data in sheet named Sheet1
// target sheet of move to named Sheet2
// test column with yes is col 7 or G
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if(s.getName() == "Under Contract Response Form" && r.getColumn() == 7 && (r.getValue() == "Closed" || r.getValue() == "Expired" || r.getValue() == "Cancelled")) {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Closed/Expired & Cancelled");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).copyTo(target);
s.deleteRow(row);
} else if(s.getName() == "Listing Response Form" && r.getColumn() == 7 && r.getValue() == "Pending" ) {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Under Contract Response Form");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).copyTo(target);
s.deleteRow(row);
} else if(s.getName() == "Listing Response Form" && r.getColumn() == 7 && r.getValue() == "Cancelled" ) {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Closed/Expired & Cancelled");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).copyTo(target);
s.deleteRow(row);
} else if(s.getName() == "Under Contract Response Form" && r.getColumn() == 7 && (r.getValue() == "Pre-list" || r.getValue() == "Withheld" || r.getValue() == "Coming Soon" || r.getValue() == "Active")) {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Listing Response Form");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).copyTo(target);
s.deleteRow(row);
} else if(s.getName() == "Closed/Expired & Cancelled" && r.getColumn() == 7 && r.getValue() == "Pending" ) {
var row = r.getRow();
var numColumns = s.getLastColumn();
var targetSheet = ss.getSheetByName("Under Contract Response Form");
var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
s.getRange(row, 1, 1, numColumns).copyTo(target);
s.deleteRow(row);
}
}

The script looks fine, so chances are that one or more sheets has been renamed, or columns inserted or deleted. Check the sheet names and look for things like leading or trailing spaces. Also ensure that the values that should trigger row move appear in column G.
You can make row moves more robust by using column names instead of column numbers. See the moveRowsFromSpreadsheetToSpreadsheet_ script.

Related

Exception based on condition on Apps Script in Google Sheet

With this script I can exclude to insert the same value column in Google Sheet for maximum 100 times.
But I am trying to exclude (with if statement) some values from this script, in particular the date "25/12/2022" and the date "12/01/2012".
How could I proceed?
function onEdit(e) {
var r = e.range;
var s = r.getSheet();
if (s.getName() === 'New Rise 2022' && r.getColumn() === 27) {
var newValue = r.getDisplayValue();
if (newValue == "") return;
var count = s.getRange('AA1:AA').getDisplayValues().filter(([a]) => a === newValue).length;
if (count > 99) {
r.setValue(e.oldValue);
SpreadsheetApp.flush();
SpreadsheetApp.getUi().alert('Questa data è stata già inserita 100 volte');
}
}
}
Update:
function onEdit(e) {
var r = e.range;
var s = r.getSheet();
if (s.getName() === 'New Rise 2022' && r.getColumn() === 27) {
var newValue = r.getDisplayValue();
if (newValue == "") return;
var count = s.getRange('AA1:AA').getDisplayValues().filter(([a]) => a === newValue).length;
if (count > 99 || e.range.getDisplayValue() == "25/12/2012" || e.range.getDisplayValue() == "12/01/2012") {
r.setValue(e.oldValue);
r.setNumberFormat('dd/mm/YYYY');
SpreadsheetApp.flush();
SpreadsheetApp.getUi().alert('Questa data è stata già inserita 100 volte');
}
}
}
How about this?
function onEdit(e) {
const sh = e.range.getSheet();
const x = ["25/12/2022","12/01/2012"];
const idx = x.indexOf(e.value);
if (sh.getName() === 'New Rise 2022' && e.range.columnStart == 27 && e.value && !~idx) {
var count = sh.getRange('AA1:AA' + sh.getLastRow()).getDisplayValues().flat().filter(e => e == e.value).length;
if (count > 99) {
e.range.setValue(e.oldValue);
}
}
}
You can get the newly entered display value and compare it against the "forbidden" values
Therefore, retrieve the latest modified cell with e.range:
...
if (count > 99 || e.range.getDisplayValue() == "25/12/2022" || e.range.getDisplayValue() == "12/01/2012") {
...
}
...
Note:
I understood that what you are interested in is the displayed value (date in this case), but depending on your date formatting the display value will be different from the value you typed in.
If it is the typed in value you are after, you can retrieve it with e.value:
...
console.log("e.value: " + e.value)
console.log("e.range.getDisplayValue(): " + e.range.getDisplayValue())
if (count > 99 || e.value == "25/12/2022" || e.value == "12/01/2012") {
...
}
...
References:
Event Objects
getDisplayValue()
UPDATE:
If you have problems with number formatting you can use the method setNumberFormat().
Modify your code block in the if statement to
r.setValue(e.oldValue);
r.setNumberFormat('dd/mm/YYYY');

Add items to an existing list mvc5

(I am a new developer)I have a list that I put in a viewBag to make a dropwdown in my view and I would like to add 3 elements to this list so that we can see them at the end of my dropdown. I make a timesheet for the employees and I have a dropdown of the projects that the person worked during the week and I would like to add at the end of the dropdown the 3 options "Vacancy", "Unplanned Absence", "Planned Absence" if the person has been on leave instead of working.
This is my request for the projects :
var projectAssignment = (from pa in db.ProjectAssignment
join p in db.Projects on pa.ProjectId equals p.ID
where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
select new ProjectTimesheetList
{
ProjectName = p.ProjectName,
ProjectId = pa.ProjectId
});
ViewBag.ProjectTimeSHeet = projectAssignment;
This is a the modal to add my timehseet and i want to put the 3 daysoff type at the end of dropdown, so in this case after "NatureBooker"
And this is my code of my dropdown:
<select name="' + row + '_' + col + '" class="custom-select" id="tsCell_' + row + '_' + col + '" data-row="' + row + '" data-col="' + col + '">' +
'<option value="">----Select----</option>#Html.Raw(projsStr)</select>';
SOLUTION:
var projectAssignment = (from pa in db.ProjectAssignment
join p in db.Projects on pa.ProjectId equals p.ID
where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
select new ProjectTimesheetList
{
ProjectName = p.ProjectName,
ProjectId = pa.ProjectId
});
List<ProjectTimesheetList> projectAssignments = projectAssignment.ToList();
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Vacancy",
ProjectId = -1,
});
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Unplanned Absence",
ProjectId = -2,
});
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Planned Absence",
ProjectId = -3,
});
ViewBag.ProjectTimeSHeet = projectAssignments;
And the result:
Still not clear what exactly you want, but if my guess is right you probably want to add "fake" projects to the enumerable you're binding to (not a list, by the way).
As long as you understand that this is absolutely wrong and grounds for being fired on the spot, here you go:
ViewBag.ProjectTimeSHeet = projectAssignment
.Concat(new[]
{
new ProjectTimesheetList
{
ProjectName = "Vacancy",
ProjectId = -1,
},
new ProjectTimesheetList
{
ProjectName = "Unplanned Absence",
ProjectId = -2,
},
new ProjectTimesheetList
{
ProjectName = "Planned Absence",
ProjectId = -3,
},
});
var myOptions = {
val1 : 'Vacancy',
val2 : 'Unplanned Absence',
val3 : 'Planned Absence',
};
var mySelect = $('#dropdownID');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
through Javascript
var ddl = document.getElementById("dropdownID");
for ( let key in myOptions )
{
var option = document.createElement("OPTION");
option.innerHTML = key
option.value = myOptions[key]
ddl.options.add(option);
}

Google Visualization : How do I perform check/uncheck with google visualization table associated checkbox?

Problem:
I am unable to perform the check and uncheck action with google visualization table associated checkbox. The checkboxes are generated dynamically based on the query value.(0/1)
Code:
function drawQuestions(queryResponse, table_container_id) {
if (queryResponse.isError()) {
alert('Error in query: ' + queryResponseData.getMessage() + ' ' + queryResponseData.getDetailedMessage());
return;
}
var questionBankResponse = queryResponse.getDataTable();
if (questionBankResponse.getNumberOfRows() === 0) {
alert('Empty rows in query: ' + );
return;
}
var questionDataTable = new google.visualization.DataTable();
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
var questionDataTableRow = new Array();
var rowCounter;
var questionHeader = questionBankResponse.getValue(0, 0);
for (rowCounter = 0; rowCounter < questionBankResponse.getNumberOfRows() ; rowCounter++) {
var count = 0 * 1;
var chbQuestion;
var questionId = questionBankResponse.getValue(rowCounter, 2);
var questionName = questionBankResponse.getValue(rowCounter, 3);
var answerValue = questionBankResponse.getValue(rowCounter, 4);
var answerOthers = questionBankResponse.getValue(rowCounter, 5);
if (answerValue === null)
answerValue = 0;
if (answerValue.toString() === "1") {
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\" checked=\"true\" />";
}
else {
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\" />";
}
if (isNaN(answerOthers))
txtAnswerOthers = "<input type=\"text\"" + "size=\"100\" id=\"" + questionId + "\"" + " value='" + answerOthers + "' name='" + answerOthers + "' />";
else
txtAnswerOthers = null;
questionDataTableRow[count++] = chbQuestion;
questionDataTableRow[count++] = questionName;
questionDataTableRow[count++] = txtAnswerOthers;
questionDataTable.addRow(questionDataTableRow);
}
for (rowCounter = 0; rowCounter < questionDataTable.getNumberOfRows() ; rowCounter++) {
questionDataTable.setProperty(rowCounter, 0, "style", "width:30px");
questionDataTable.setProperty(rowCounter, 1, "style", "width:100%");
}
var tableObject = new google.visualization.Table(document.getElementById(table_container_id));
tableObject.draw(questionDataTable, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
Issue: Checkbox state has not been changed before and after the click.
Referred: Previous answer reference
Finally, I developed a solution for this. Here it is.
First, draw the table using google visualization API then draw the checkbox using HTML dom.
function handleQuestionsSqlQueryResponse(dataQueryQuestionsResponse) {
if (dataQueryQuestionsResponse.isError()) {
alert('Error in query: ' + dataQueryQuestionsResponse.getMessage() + ' ' + dataQueryQuestionsResponse.getDetailedMessage());
return;
}
var dtQuestions = dataQueryQuestionsResponse.getDataTable();
var intNoOfRows = dtQuestions.getNumberOfRows();
for (intRowCounter = 0; intRowCounter < intNoOfRows ; intRowCounter++) {
var tblQuestions = new google.visualization.DataTable();
tblQuestions.addColumn('string', '');
tblQuestions.addColumn('string', '');
var arrQuestions = new Array();
var strQuestionSection = dtQuestions.getValue(intRowCounter, 0);
var strQuestionDetails = dtQuestions.getValue(intRowCounter, 1);
if (strQuestionSection !== null && strQuestionDetails !== null) {
arrQuestions = strQuestionDetails.split(";");
for (var intRowIterator = 0; intRowIterator < arrQuestions.length; intRowIterator++) {
var intCount = 0 * 1;
var tblQuestionsRow = new Array();
var strQuestionNo = arrQuestions[intRowIterator].split("|")[0];
var strQuestionName = arrQuestions[intRowIterator].split("|")[1];
tblQuestionsRow[intCount++] = strQuestionName;
if (strQuestionName === "Other / Unknown? Please Describe:") {
tblQuestionsRow[intCount++] = "<input type=\"text\"" + "size=\"30\" id=\"" + strQuestionNo + "Others" + "\"" + " value='' name='" + strQuestionNo + "' disabled />";
} else {
tblQuestionsRow[intCount++] = null;
}
tblQuestions.addRow(tblQuestionsRow);
}
var tableObject = new google.visualization.Table(document.getElementById(strQuestionSection));
tableObject.draw(tblQuestions, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
}
}
for (intRowCounter = 0; intRowCounter < intNoOfRows ; intRowCounter++) {
var intQuestionValue = 0;
var strQuestionSection = dtQuestions.getValue(intRowCounter, 0);
var strQuestionDetails = dtQuestions.getValue(intRowCounter, 1);
var tblContainer = document.getElementById(strQuestionSection);
var tblReference = tblContainer.getElementsByTagName('TBODY')[0];
arrQuestions = strQuestionDetails.split(";");
for (var intRowIterator = 0; intRowIterator < arrQuestions.length; intRowIterator++) {
var tblRow = tblReference.rows[intRowIterator];
var tblCheckBox = tblRow.insertCell(0);
var strQuestionNo = arrQuestions[intRowIterator].split("|")[0];
if (strQuestionNo !== null) {
tblCheckBox.innerHTML = "<input type=\"checkbox\"" + " id=\"" + strQuestionNo + "\" name=\"" + strQuestionNo + "\" value=\"" +
intQuestionValue + "\" onchange=\"doCheckOrUnCheck('" + strQuestionNo + "');\" />";
}
}
}
}

Drill down in google charts

I am trying to implement a drill in or drill down in a pie chart. I actually have a working drill down pie chart, however, when I changed the values of the collection, it did not work. I am wondering what went wrong as I completely followed the working code and just replaced its values. The chart simply does not show up and has an error: Uncaught Error: Unknown header type: 17format+en,default+en,ui+en,controls+en,corechart+en.I.js:191. I am not sure though whether this error is related to the problem.
Javascript:
google.load('visualization', '1', {packages: ['corechart', 'controls']});
google.setOnLoadCallback(drawChart1);
var index = 0;
function drawChart1() {
<%
int aku = 0, cdu = 0, ls = 0, ptr = 0, rad = 0, oper = 0;
int aku1 = 0, aku2 = 0, aku3 = 0, aku4 = 0, aku5 = 0;
int cdu1 = 0, cdu2 = 0, cdu3 = 0, cdu4 = 0, cdu5 = 0, cdu6 = 0;
int ls1 = 0, ls2 = 0, ls3 = 0, ls4 = 0, ls5 = 0, ls6 = 0, ls7 = 0, ls8 = 0, ls9 = 0, ls10 = 0;
int ptr1 = 0, ptr2 = 0, ptr3 = 0, ptr4 = 0;
int rad1 = 0, rad2 = 0, rad3 = 0;
int oper1 = 0;
%> //Dummy values
//Main
var main = [
['Artificial Kidney Unit', <%=aku%>],
['Cardiac Diagnostic Unit', <%=cdu%>],
['Laboratory Services', <%=ls%>],
['Physical Therapy and Rehabilitation', <%=ptr%>],
['Radiology', <%=rad%>],
['Operations', <%=oper%>]
];
//Aku
var akuu = [
['Hemodialysis', <%=aku1%>],
['Peritoneal Dialysis', <%=aku2%>],
['Continuous Renal Replacement Therapy', <%=aku3%>],
['Sustained Low Efficient Dialysis', <%=aku4%>],
['Private Dialysis Suite', <%=aku5%>]
];
//Cdu
var cduu = [
['Electrocardiography', <%=cdu1%>],
['Ambulatory Electrocardiography', <%=cdu2%>],
['Exercise Stress Test', <%=cdu3%>],
['2D Echo', <%=cdu4%>],
['Lower Extremity Arterial & Venous Color Duplex Scan', <%=cdu5%>],
['Carotid Artery Duplex Scan', <%=cdu6%>]
];
//Ls
var lss = [
['Hematology', <%=ls1%>],
['Blood Chemistry', <%=ls2%>],
['Immunology and Serology', <%=ls3%>],
['Clinical Microscopy', <%=ls4%>],
['Microbiology', <%=ls5%>],
['Blood Bank and Transfusion Services', <%=ls6%>],
['Drug Testing', <%=ls7%>],
['Parasitology', <%=ls8%>],
['Surgical Pathology', <%=ls9%>],
['Cytopathology', <%=ls10%>]
];
//Ptr
var ptrr = [
['Physical Therapy', <%=ptr1%>],
['Occupational Therapy', <%=ptr2%>],
['Ultrasound Diagnostic Therapy', <%=ptr3%>],
['Orthotics and Prosthetic Evaluation', <%=ptr4%>]
];
//rad
var radd = [
['X-ray', <%=rad1%>],
['Ultrasound', <%=rad2%>],
['CT Scan', <%=rad3%>]
];
//oper
var operr = [
['Surgery', <%=oper1%>]
];
var collection = [];
collection[0] = google.visualization.arrayToDataTable(main);
collection[1] = google.visualization.arrayToDataTable(akuu);
collection[2] = google.visualization.arrayToDataTable(cduu);
collection[3] = google.visualization.arrayToDataTable(lss);
collection[4] = google.visualization.arrayToDataTable(ptrr);
collection[5] = google.visualization.arrayToDataTable(radd);
collection[6] = google.visualization.arrayToDataTable(operr);
var options1 = {
title: 'Departments',
animation: {'duration': 500,
'easing': 'in'},
action: function() {
button.onclick = function() {
recreateDashboard(0);
};
}
};
var chart1 = new google.visualization.PieChart(document.getElementById('chart1'));
google.visualization.events.addListener(chart1, 'select', drillIn);
google.visualization.events.addListener(chart1, 'click', drillOut);
chart1.draw(collection[0], options1);
function drillIn() {
var sel = chart1.getSelection();
var row = chart1.getSelection()[0].row;
options1['title'] = collection[index].getValue(sel[0].row, 0);
if(index === 0) {
if(row === 0) {
index = 1;
}
if(row === 1) {
index = 2;
}
if(row === 2) {
index = 3;
}
if(row === 3) {
index = 4;
}
if(row === 4) {
index = 5;
}
if(row === 5) {
index = 6;
}
}
else if(index === 1 || index === 2 || index === 3 || index === 4 || index === 5 || index === 6) {
options1['title'] = '# of services rendered in <%=year%>';
index = 0;
}
chart1.draw(collection[index], options1);
}
function drillOut(e) {
if(e.targetID === "title") {
if(index !== 0)
index--;
else if(index === 4 || index === 6 || index === 8)
index -= 2;
chart1.draw(collection[index], options1);
}
}
Html:
<div id="chart1">
</div>
I have figured out the mistake. All of these need a title before inputting the values.
Revised code:
//Main
var main = [
['Department', 'Value'],
['Cardiac Diagnostic Unit', <%=cdu%>],
['Laboratory Services', <%=ls%>],
['Physical Therapy and Rehabilitation', <%=ptr%>],
['Radiology', <%=rad%>],
['Operations', <%=oper%>]
];
//Aku
var akuu = [
['Service', 'Value'],
['Hemodialysis', <%=aku1%>],
['Peritoneal Dialysis', <%=aku2%>],
['Continuous Renal Replacement Therapy', <%=aku3%>],
['Sustained Low Efficient Dialysis', <%=aku4%>],
['Private Dialysis Suite', <%=aku5%>]
];
//Cdu
var cduu = [
['Service', 'Value'],
['Electrocardiography', <%=cdu1%>],
['Ambulatory Electrocardiography', <%=cdu2%>],
['Exercise Stress Test', <%=cdu3%>],
['2D Echo', <%=cdu4%>],
['Lower Extremity Arterial & Venous Color Duplex Scan', <%=cdu5%>],
['Carotid Artery Duplex Scan', <%=cdu6%>]
];
//Ls
var lss = [
['Service', 'Value'],
['Hematology', <%=ls1%>],
['Blood Chemistry', <%=ls2%>],
['Immunology and Serology', <%=ls3%>],
['Clinical Microscopy', <%=ls4%>],
['Microbiology', <%=ls5%>],
['Blood Bank and Transfusion Services', <%=ls6%>],
['Drug Testing', <%=ls7%>],
['Parasitology', <%=ls8%>],
['Surgical Pathology', <%=ls9%>],
['Cytopathology', <%=ls10%>]
];
//Ptr
var ptrr = [
['Service', 'Value'],
['Physical Therapy', <%=ptr1%>],
['Occupational Therapy', <%=ptr2%>],
['Ultrasound Diagnostic Therapy', <%=ptr3%>],
['Orthotics and Prosthetic Evaluation', <%=ptr4%>]
];
//rad
var radd = [
['Service', 'Value'],
['X-ray', <%=rad1%>],
['Ultrasound', <%=rad2%>],
['CT Scan', <%=rad3%>]
];
//oper
var operr = [
['Service', 'Value'],
['Surgery', <%=oper1%>]
];

Split String not Meeting Conditions [Swift]

I'm trying to take a series of numbers from a text file and based on the numbers define a new variable. When I print SettingsArray i get the following:
[10, 25, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0.02, 0.002, 0, 1, 0, 0, 0, 1, 1, 1, 25, 500, 0, 1, 250, 250, 250, 500, 500, 500, 10, 10, 10, 200, 200, 200]
Which are the numbers I'm looking for, but for some reason, when checking the If statements, all of the SettingsArray elements look something like this:
[2] String class name = _TtC10Foundation15_NSOpaqueString
Which obviously don't meet any of the conditions, why are the array elements garbled when checking the If statements?
let file = String(contentsOfFile: "/Users/UserGoesHere/Documents/Settings.txt", encoding: NSUTF8StringEncoding, error: nil)!
var SettingsArray = split(file) {$0 == ","}
var StepPortInvert = ""
if SettingsArray[2] == "1" && SettingsArray[3] == "1" && SettingsArray[4] == "1" {
var StepPortInvert = "00000000"
}
if SettingsArray[2] == "0" && SettingsArray[3] == "1" && SettingsArray[4] == "1" {
var StepPortInvert = "00000001"
}
if SettingsArray[2] == "1" && SettingsArray[3] == "0" && SettingsArray[4] == "1" {
var StepPortInvert = "00000010"
}
You just have to declare StepPortInvert once. BTW 2,3,4 = "1, 0, 0"
let file = String(contentsOfFile: "/Users/UserGoesHere/Documents/Settings.txt", encoding: NSUTF8StringEncoding, error: nil)!
var SettingsArray = split(file) {$0 == ","}
var StepPortInvert = ""
if SettingsArray[2] == "1" && SettingsArray[3] == "1" && SettingsArray[4] == "1" {
StepPortInvert = "00000000"
}
if SettingsArray[2] == "0" && SettingsArray[3] == "1" && SettingsArray[4] == "1" {
StepPortInvert = "00000001"
}
if SettingsArray[2] == "1" && SettingsArray[3] == "0" && SettingsArray[4] == "1" {
StepPortInvert = "00000010"
}