Saturday, March 24, 2012

So I've tried to start embracing coffeescript that is used in Rails 3.1, I guess it's the thing to do or something.

Anyway, I'm also using the jquery and that's all good and fine. The issue I was having is this:

I've got a form and I want it to be as easy as possible for the user to understand it and fill it out. I've got a dropdown box (or select) on this form and depending on the value I want to make little changes in the form take place to make the form easier for the user.

No problem, add some jquery to handle the change() event, show() or hide() somethings and shazam, things make more sense.

Great. So now the user saves the form and comes back to it to edit something and all those little changes that were made are no longer there. Hrm. Well, I could set the initial state of the form by adding a bunch of code to set the default values of the style's and whatever else needs to be changed but this is ugly and means putting style or js code in my view which I would rather not do.

So why not just add some code to handle the ready() event on the page, problem is the dom is initialized but the values in the form have not been set yet and my function relies on those values to work properly. I then fiddled around with trying to get a function to be called after the page was finished loading and rendering and all that but nothing was working well.

Then I found a tip on the internet suggesting to just call the change() function on the form element from the ready() event of the page. Seems like it wouldn't work because the values are not set but it turns out the change call is only handled after everything (well, everything that I need) is setup so boom. Fixed and no ugliness!

The coffeescript code:

$ -> $('#my_id').change()

No comments:

Post a Comment