View Full Version : for() in javascript

08-25-2011, 05:48 AM
searched web and cant find which way to go with this. I am trying to amend a date timepicker calender.

the function contains two incemented values for hour and minute. i alterd the values of the hours to suitable opening hours. but in lost with minutes. this is also a for() loop using i++, but what i would like is 2 values ie on the hour and 30 mins. so can i specify the increment for i , or would this need re writing (while loop?)
cant find where to look for clues . the relevant part of the method

var selectContainer = new Element('div', {className: 'selectContainer'});
selectContainer.appendChild(new Element('div').update('Select time:'));
this.hours = new Element('select');
this.minutes = new Element('select');

for (var i=9; i<17; i++) {
this.hours.appendChild(new Element('option').update(i < 10 ? '0' + i : i));

for (var i=0; i<60; i++) {
this.minutes.appendChild(new Element('option').update(i < 10 ? '0' + i : i));


08-25-2011, 06:25 AM
found it javascriptkit.com tutorials

for (var i=30; i<=60; i=i+30) {
this.minutes.appendChild(new Element('option').update(i < 10 ? '0' + i : i));
sorry javascript i tke back all those badnames i called you :)

08-25-2011, 08:26 PM
Consider this part in your code

i < 10 ? '0' + i : i

It is basically a shortcut if statement that says if i is less than 10 prepend i with a 0 else, just let i be i

so the code makes 1 = 01, 2 = 02 and so on but lets 10 = 10, 11=11 and so on..

Now look at your for initialization and conditions

var i=30; i<=60; i=i+30

if you analyze the code you have only 2 possible values of i, 30 and 60, never less than 10 and so the first bit of code (i < 10 ? '0' + i : i) is unnecessary!

So this line

this.minutes.appendChild(new Element('option').update(i < 10 ? '0' + i : i));

can be safely be changed to

this.minutes.appendChild(new Element('option').update(i));

08-26-2011, 12:50 AM
thanks ranjan i had wondered about that part.
i had lost my nerve a bit as id had a few stab in the dark attempts which as a fauly script managed to freeze firefox and in turn my pc so i was getting abit rattled :)