1

So I've got 43 Radio buttons. When one of them is selected, it returns their index number. It's zero-based, so its 0-42. Each index corresponds to a particular time. 0 is 8:00am and 42 is 10:00pm, each index increase the time for 20 minutes. Essentially, I'm trying to generate the time I need without having to manually create if-statements for each index. Here's the broken code I have so far.

function decipherIndex(radx) {
    var actime = "";
    var hr = 8;
    var min = 0;
    var day = "am";
    for (i=0;i<radx;i++) {
        min = min + 20;
        if (min = 60) {
            hr = hr + 1;
            min = 0;
        }
        if (hr = 13) {
            hr = 0;
            day = "pm";
        }
    }
    actime = hr + ":" + min + day;
    alert(actime);
}

Hopefully someone can help me work through my logic here. radx is the index that's getting passed to the function.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Vikram
  • 349
  • 3
  • 7
  • 16

1 Answers1

3
if (min = 60) {
    hr = hr + 1;
    min = 0;
}
if (hr = 13) {
    hr = 0;
    day = "pm";
}

You're assigning with the =, so min and hr will always be 0 and day will always be "pm". Use == or === to compare:

if (min == 60) {
    hr = hr + 1;
    min = 0;
}

if (hr == 13) {
    hr = 0;
    day = "pm";
}

However, a loop isn't necessary; all you need is a little bit of math.

function decipherIndex(i) {
    var t = 60 * 8 + i * 20;
    var min = t % 60;
    var hr = t / 60 | 0;

    return hr % 12 + ':' + (min < 10 ? '0' : '') + min + (hr >= 12 ? ' PM' : ' AM');
}
Ry-
  • 218,210
  • 55
  • 464
  • 476