Android-Esque Time Entry Widget doesn't work when minutes section is below ten

Go To StackoverFlow.com

2

I'm trying to make a "widget" used for controlled time entry that uses up and down arrows to increment each section in addition to allowing you to type the values in by hand. It worked fine(looping over from 12 to 1 and 59 to 1 ect.), but when I added a section that formatted the minutes properly when the value was below 10, it started acting up.

Pressing down acts normally until 10 where it displays, "10" then "09" then "0-1".

Pressing up after you get to "0-1" goes to "01" but when you get to "08", it goes back to "01".

function minFix(mins)
{
if ( mins <= 9)
    {
        mins = "0" + String(mins);
        document.getElementById("mins").value = mins;
    }
else
    {
        document.getElementById("mins").value = mins;
    }
}


function minUp()
{
var mins = parseInt(document.getElementById("mins").value);
if (mins == 59)
    {
        mins = 1;
        minFix(mins);
    }
else
    {
        mins = (mins+1);
        minFix(mins);
    }
}


function minDown()
{
var mins = parseInt(document.getElementById("mins").value);
if (mins == 1)
    {
        mins = 59;
        minFix(mins);
    }
else
    {
        mins = (mins-1);    
        minFix(mins);   
    }

}

The minUp and minDown are called by the up and down arrows respectively and the textbox that displays mins has an ID of mins.

I'm sure I'm missing something simple but I can't figure it out right now so any help would be much appreciated.

2012-04-04 19:06
by Will Meldon


1

this has to do with your zero that you're appending. It makes your number into a octal number, so when you read it back in, it's not being read as a decimal number. Take a look at how parseInt works and you'll understand. You need to remove the leading zero before parsing.

Scroll down for the parseInt function here: http://www.javascripter.net/faq/convert2.htm

so this line var mins = parseInt(document.getElementById("mins").value);

should be

var mins = parseInt(document.getElementById("mins").value.replace(/^0+/,""));

Oh, and welcome to Stack! please don't forget to up-vote the answers that you feel are best, and give the green checkmarks to those that you feel are the correct ones.

2012-04-04 19:11
by Genia S.
Thank you very much. That explains it perfectly - Will Meldon 2012-04-04 19:16
You're welcome! Hit the green checkmark next to my answer, please : - Genia S. 2012-04-04 19:18
For the record, the way I changed it to work was by defining the parse as base ten rather than removing the zero. mins = parseInt(document.getElementById("mins").value, 10);Will Meldon 2012-04-04 19:19
perfect. I just noticed that the 0 based octal reading of the number has been deprecated anyway, so, maybe it'll just go away at some point. And you're right, your usage is probably more efficient than my invocation of regular expressions. Good catch - Genia S. 2012-04-04 19:27
Ads