HomeBlogWriting dynamically generated Javascript

Writing dynamically generated Javascript

Published March 25, 2004
This week I had the need to write a rather complicated/messy piece of JavaScript. The basic task was as follows. We had 2 sets of 3 drop downs. Each set of 3 represented a time in a 24 hour day. The first one was an hour dropdown (between 1 and 12), the second drop down was minutes (between 00 and 59 OR the same in 5 minute increments) and the last dropdown was AM/PM. The second drop down was the same as above. We had to write some code that worked out the hours between the 2 sets. E.g. If you selected 5 40 AM in the first dropdown and 6 40 AM in the second drop down, then we had a little text box on the side that displays 1 (i.e. the time between the 2 sets of dropdowns. This was implemented with JavaScript). In itself, this turned out to be more complicated that it looks like at first glance. We implemented the code so that the first set of dropdowns was the START time and the 2nd set was END time. If you chose start time as 6:40AM and end time as 6:30 AM, it gives almost 24 hours, but the other was around gives 10 minutes.... but as all resourceful programmers, we got around this and got it to work. The main reason I am writing this blog, is not for this, but for another reason. We soon realized that this method (using JavaScript to calculate the times between the dropdowns) was not really expandable to more than one set of times (6 dropdowns). The reason being that we would change the hour number on the side on the onChange() event. Using one set of times (6 dropdowns) we could hardcode and tie down all of the dropdowns to the same onChange event.. Suddenly we need 6 sets of times (36 dropdowns) and we are in a muddle. So we decided to do it the lazy, PHP way, using PHP classes to write the JavaScript dynamically. We created a PHP class that wrote out the JavaScript for 1 dropdown (with enabled, checked, hidden etc all available as parameters to this class). We made another class that calls this one TWICE and places both sets on a common platform (“plaque”). Now that we have 2 sets tied on a common plaque, we could then use PHP to dynamically write the JavaScript for the summary hours. It is totally expandable, easy to use (all you need is 3 calls, one for each dropdown and one for the hour display ) and it is totally expandable to as many times you want. A really good educational experience as well as a fun challenge. Bye for Now and till l8r Uriel
blog comments powered by Disqus


Connect With Us

Send Us a Message

Do you wish to give us feedback on one of our apps, send us a message or explore a proposal? Fill out the form below and we'll get back to you pronto!

Visit Us

250 West Nyack Road, Suite #200 West Nyack, NY 10994
Get Directions

Call Us Toll Free