I initially began my task by trying to use JS best practices when writing this code, but I was struggling, so I just wrote it as a big sloppy mess to get it to work, and then tried to clean it up after the fact. (You may argue that that wasn’t a good idea, but it was the best I could do with where I am.)
My boss suggested I try to use custom triggers and events, but that didn’t really seem the best route. I also read this article by Rebecca Murphy on OOJS that seemed like it might have an answer, but I just couldn’t get there.
Keep in mind that, while I’m definitely specifically looking for a more elegant (and less nested-if-statement-dependent) way to write this and definitely appreciate any help on that matter, I’m also looking for patterns that could help me address my larger stylistic shortcomings here and become a better programmer. For example, I know that this is the clunkiest and slowest way to traverse the DOM.
One important note: I can’t control much of the markup (aside from adding classes as JS/CSS hooks) in this situation, because it’s being generated by the SimpleForm Ruby gem (I’m unable to link to it because of my low score). And the CSS is irrelevant. So it’s really just the JS.
Context
Certain things are being shown/hidden based on select or radio button choices.
EDIT: Sorry, my HTML was getting weird here, so I just made a jsFiddle.
EDIT 2: We’re using jQuery 1.6.4, so if you’re wondering why I used .delegate instead of .on, that’s why.
You could also keep things DRY by removing the duplicated code to show/hide items. Here is a very simplistic approach that improves things:
and then to use the function, simply give it the selectors to show, and to hide respectively: