'PineScript: Barcolor based on Input

Complete newbie looking for help.

Currently I color my bars using a simple code.

barclr = input(false, title='(Off) Color2 or (On) Color1')
barcolor(barclr ? barcolor2 : barcolor1)

I now want to color bars only if another toggle says "Yes" and so I created,

bar = input.string("Yes", title="Colored Bars", options=["Yes", "No"]) == "Yes" 

So now what I want to happen is when the bar dropdown is set to "Yes" then color bars otherwise don't color bars at all.

Also while bar == "Yes" then use barclr to switch between two options.

(I don't have a preference if it's a toggle or dropdown but just for my limited sense of differentiation I tried using a dropdown.)

I don't know how to put this together. Please help.



Solution 1:[1]

You have almost accomplished a goal, add a new ternary check for the bar input and nest the existing ternary condition inside barcolor() function:

//@version=5
indicator("My script")

bar = input.string("Yes", title="Colored Bars", options=["Yes", "No"])
barclr = input(false, title='(Off) Color2 or (On) Color1')

barcolor1 = color.red
barcolor2 = color.green

barcolor(bar == "Yes" ? barclr ? barcolor1 : barcolor2 : na)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 e2e4