Why won't my CoffeeScript if/else statement work? - if-statement

I've been trying to update a total price when someone changes the select option. Here is the select element I'm using:
<select id="payment_talks_purchased" name="payment[talks_purchased]">
<option value="1">One</option>
<option value="2">Three</option>
</select>
This is the jQuery I'm using:
jQuery(document).ready(function() {
var price = $(".total-price span.price")
var save = $(".savings")
$("#payment_talks_purchased").change(function() {
var selection = $("#payment_talks_purchased").val()
if (selection == 2) {
price.html("$12");
save.css("visibility", "visible");
} else if (selection == 1) {
price.html("$5");
save.css("visibility", "hidden");
}
});
});
It works perfectly. It changes the price to $12 and shows the discount message. If I change the select option back to One/1, it changes the text back to $5 and removes the discount message.
I converted this to CoffeeScript but it only works when I make the first change. The price is updated. However, when I try to change it back to option 1, it doesn't update.
jQuery ->
price = $(".total-price span.price")
save = $(".savings")
select = $("#payment_talks_purchased")
select.change ->
selection = select.val()
if selection = 2
price.html "$12"
return save.css "visibility", "visible"
else if selection = 1
price.html "$5"
return save.css "visibility", "hidden"
I've been working on this for hours and am at my wits end. Any help would be greatly appreciated.

Your selection = 1 inside your if statements is (still) an assignment in CoffeeScript, you need to use == for comparison. Try this:
jQuery ->
price = $(".total-price span.price")
save = $(".savings")
select = $("#payment_talks_purchased")
select.change ->
selection = select.val()
if selection == '2'
price.html "$12"
return save.css "visibility", "visible"
else if selection == '1'
price.html "$5"
return save.css "visibility", "hidden"
Also, == is converted to === so you'll want to compare against strings unless you want to "cast" your value to a number using selection = +select.val() (thanks to Trevor Burnham for this casting trick) or parseInt(select.val(), 10).

You can use switch:
switch selection
when '2'
price.html "$12"
save.css "visibility", "visible"
when '1'
price.html "$5"
save.css "visibility", "hidden"
Also you can take away return, because functions will always return their final value.

Here is my .50 cents. Take in consideration 2 things: its just my simple opinion and it can be not the best answer of the world.
a) If you already have a return inside IF statement, no need ELSE IF
jQuery ->
price = $(".total-price span.price")
save = $(".savings")
select = $("#payment_talks_purchased")
select.change ->
selection = select.val()
if selection == '2'
price.html "$12"
// Since you return here, you dont need any other "else if"
return save.css "visibility", "visible"
price.html "$5"
return save.css "visibility", "hidden"
And no, IMHO, puts the ELSE IF doesnt improve the readability. Return is a return. Period. It is simple as that.
jQuery ->
price = $(".total-price span.price")
save = $(".savings")
select = $("#payment_talks_purchased")
select.change ->
selection = select.val()
// "ternary" coffee version (if then else)
price.html if selection == '2' then "$12" else "$5")
save.css "visibility" (if selection == '2' then "visible" else "hidden")
But, better than all is get rid of IF, ELSE, SWITCH and all those craps. Think OOP and your code can start getting better. A starting point could be:
options = [
{price: '$12', visible:"visible"},
{price: '$5', visible:"hidden"}
];
jQuery ->
price = $(".total-price span.price")
save = $(".savings")
select = $("#payment_talks_purchased")
select.change ->
// If the val of your select was 0 and 1, you wouldnt need the (-1) part
selection = parseInt(select.val) -1
price.html options[selection].price
save.css "visibility" options[selection].visible
So, this is it. Almost the same code, but with a better implementation (imho). Thank you.

Related

Google script insert value in a column if another column has a specific value

as basic as this may sound I am having difficulty writing this. I have two columns with checkboxes in a sheet(main) and I want to be able to checkbox(true) column 'O' if column 'm' has a checkmark after I am done with the sheet(macro button).
Thanks for any input.
If M is true set O to true
function lfunko() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const [hA,...vs] = sh.getDataRange().getValues();
vs.forEach((r,i) => {
if(r[12] == "TRUE") {
sh.getRange(i + 2, 15).setValue("TRUE");
}
})
}

How to create a measure that can mark two columns conditionally?

I have a table that is something like this:
ID
A
B
1H4
6S8
True
1L7
True
6T8
True
7Y8
6S2
True
True
1H1
True
6S3
True
1H9
True
True
6S0
I want to create a measure that evaluates a table to be able to conditionally (to later make conditional rules for report i.e. place color values in such cells) evaluate the cells for the following 2 conditions:
when there are values in both Column A and Column B
when there are blanks/nulls in both columns
(If both can be done in a single measure this would be ideal)
You can use a measure like this:
Background Color =
var Count_A = COUNTBLANK('Table'[A])
var Count_B = COUNTBLANK('Table'[B])
RETURN
SWITCH(TRUE();
AND(Count_A = 0; Count_B = 0); "Red";
AND(Count_A > 0; Count_B > 0); "Green";
"")
First count the blank values in each of the columns, and then return a different color, depending on both counts. Then use this measure to conditionally format the background color for each of the columns:
to get something like this:
You'll need a custom column with the logic of
Column name =
SWITCH (
TRUE (),
A = 'True'
&& B = 'True', "True",
A = ''
&& B = '', "False",
"Else goes here"
)
You'll have to change the logic if the cells without anything in them are '' or true blanks. SWITCH acts like a multiple IF statement, and Switch with TRUE() evaluates the conditions in the later steps.
You can achieve the desired result by using both custom columns and measures.
Custom Column
Column =
IF (
Table[A] <> BLANK ()
&& Table[B] <> BLANK (),
"Green",
IF ( Table[A] = BLANK () && Table[B] = BLANK (), "Red" )
)
Measure
Measure X =
IF(COUNTBLANK(Table[A]) = 0
&& COUNTBLANK(Table[B]) = 0 , "#00FF00",
IF(COUNTBLANK(Table[A]) <> 0
&& COUNTBLANK(Table[B]) <> 0 , "#FF0000")
)
After creating a measure or custom column go to conditional formatting and select background colour, and you may select either measure or column as per your choice. this will give you the desired result.
Output

EXPAND MULTIPLE COLUMNS POWER BI

I´ve been struggling with this:
My table shows 3 records but when expanding there are like 100 columns. I used this code:
#"Expanded Data" = Table.ExpandTableColumn(#"Source", "Document", List.Union(List.Transform(#"Source"[Document]), each Table.ColumnNames(_))),
but it's not working. How can I expand simultaneously all columns? Also, inside those columns there are even more, for example I expand the first time end then those new columns have more records inside.
What could I do? Thanks in advance!
Try this ExpandAllRecords function - it recursively expands every Record-type column:
https://gist.github.com/Mike-Honey/0a252edf66c3c486b69b
This should work for Records Columns.
let
ExpandIt = (TableToExpand as table, optional ColumnName as text) =>
let
ListAllColumns = Table.ColumnNames(TableToExpand),
ColumnsTotal = Table.ColumnCount(TableToExpand),
CurrentColumnIndex = if (ColumnName = null) then 0 else List.PositionOf(ListAllColumns, ColumnName),
CurrentColumnName = ListAllColumns{CurrentColumnIndex},
CurrentColumnContent = Table.Column(TableToExpand, CurrentColumnName),
IsExpandable = if List.IsEmpty(List.Distinct(List.Select(CurrentColumnContent, each _ is record))) then false else true,
FieldsToExpand = if IsExpandable then Record.FieldNames(List.First(List.Select(CurrentColumnContent, each _ is record))) else {},
ColumnNewNames = List.Transform(FieldsToExpand, each CurrentColumnName &"."& _),
ExpandedTable = if IsExpandable then Table.ExpandRecordColumn(TableToExpand, CurrentColumnName, FieldsToExpand, ColumnNewNames) else TableToExpand,
NextColumnIndex = CurrentColumnIndex+1,
NextColumnName = ListAllColumns{NextColumnIndex},
OutputTable = if NextColumnIndex > ColumnsTotal-1 then ExpandedTable else #fx_ExpandIt(ExpandedTable, NextColumnName)
in
OutputTable
in
ExpandIt
This basically takes Table to Transform as the main argument,and then one by one checks if the Column Record is expandable (if column has "records" in it, it will expand it, otherwise move to next column and checks it again).
Then it returns the Output table once everything is expanded.
This function is calling the function from inside for each iteration.

Declaring variables in Power Query M Functions

I am trying to create a reusable function in Power Query that will be used by several tables.
This works well (written in blank query):
let
is_emergency = (color as text) =>
if color = "red" or color = "orange" then
"emergency"
else
"not emergency"
in
is_emergency
I can call it using a custom column like this =emergency([color_column]).
However - my color column contains a lot of extra spaces so I somehow need to call Text.Trim() on the color-parameter. How to write this?
What I thought would work was to just write this:
let
is_emergency = (color as text) =>
color = Text.Trim(color, " "),
if color = "red" or color = "orange" then
"emergency"
else
"not emergency"
in
is_emergency
but this gives me the error Token Literal Expected.
How to write it proper? I am aware I can use the Power Query GUI to create simple functions like this, but my real case is more advanced and I would like to understand the M syntax.
I managed to solve it myself after some research.
let
is_emergency = (color as text) =>
// you need to put the variable declaration inside a new let - in
let
trimmed_color = Text.Trim(color, " "),
// you also need to define the return value and return it in the new let - in
return_value = if trimmed_color = "red" or trimmed_color = "orange" then
"emergency"
else
"not emergency"
in
return_value
in
is_emergency

Crystal Report converting value to number with symbol

I have an issue with a Crystal Report that I'm creating. I am using fields from a database and am pulling in the result value where the analysis field is equal to certain values.
In the condition the first check looks at the analysis field and checks if its equal to "Conf". The result for this is "<10"
The second check looks at the analysis field and checks if its equal to "Original". The result for this is "20".
I want the results to display in the order above however with the following basic logic it returns the result of 20.
if analysis = "conf" then result
else if analysis = "Original" then result
I was having this issue with multiple records however solved it by converting both results to numbers (toNumber(Result)). However this record has the less than symbol contained within the field value which causes the conf result to "be skipped" and will display the original result instead. I've tried a few things without success. Here is the code for the condition of where I'm at below. I fell this is way to complex logic but I've just added to it as I've had ideas and it shows what I've tried.
if {UNITS} = "CFU_G" then
if {ANALYSIS} = "CONF" and
{RESULT}="" or
{RESULT} = "0" then 0
else if {ANALYSIS} = "CONF"
then if isNumeric({RESULT}) then
tonumber({RESULT}) else
tonumber(Replace ({RESULT}, "<", ""))
else
if {UNITS} = "CFU_G" then
if {ANALYSIS} = "Original" and
{RESULT}="" or
{RESULT} = "0" then 0
else if {ANALYSIS} = "Original"
then if isNumeric({RESULT}) then
tonumber({RESULT}) else
tonumber(Replace ({RESULT}, "<", ""))
Thanks,
Tom
This was the solution I came up with.
Field 1
whileprintingrecords;
stringvar vResult := "";
Field 2
whileprintingrecords;
stringvar vResult;
vResult := if {RESULT.UNITS} = "CFU_G"
and {RESULT.ANALYSIS} = "CRA_LIS_ENU_CONF_MPCRAM29"
then {RESULT.FORMATTED_ENTRY}
else if {RESULT.ANALYSIS} = "CRA_LIST_ENU_MPCRAM29"
and {RESULT.UNITS} = "CFU_G"
and vResult = ""
then {RESULT.FORMATTED_ENTRY}
Field 3
whileprintingrecords;
stringvar vResult;
vResult;