user1914374
user1914374

Reputation: 1260

How to create a count up timer in a text input?

Below I have a javascript count down timer which works fine:

    <h1><span id='countdown'><?php echo $dbSessionDuration; ?></span></h1>

...

  $(document).ready(function() {
    var time = <?php echo json_encode($dbSessionDuration); ?>,
      parts = time.split(':'),
      hours = +parts[0],
      minutes = +parts[1],
      seconds = +parts[2],
      span = $('#countdown');


    function correctNum(num) {
      return (num<10)? ("0"+num):num;
    }

    var timer = setInterval(function(){
        seconds--;
        if(seconds == -1) {
            seconds = 59;
            minutes--;

            if(minutes == -1) {
                minutes = 59;
                hours--;

                if(hours==-1) {
                  alert("timer finished");
                  clearInterval(timer);
                  return;
                }
            }
        }
        span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
    }, 1000);

});

Now what I thought of doing is use the example above and manipulate it to now do the opposite and create a count up timer starting with 00:00:00 (hours, mins, secs).

But issue is that it is not working. Nothing is happening. I don't know if I need an hours in the function below because as its a countup, the hours could go up to as many hours as it wants. But my question is how can the count up timer be fixed so that it is fully working?

<p><input type='text' class='responseTime' name='responsetime' value='00:00:00' /></p>

...

$(document).ready(function() {
var response = "00:00:00",
      parts = time.split(':'),
      hours = +parts[0],
      minutes = +parts[1],
      seconds = +parts[2],
      input = $('.responseTime');


    function correctResponse(responsenum) {
      return (responsenum<10)? ("0"+responsenum):responsenum;
    }

    var responsetimer = setInterval(function(){
        seconds--;
        if(seconds == +59) {
            seconds = 00;
            minutes--;

            if(minutes == +59) {
                minutes = 00;
                hours--;

                  return;

            }
        }
        input.text(correctResponse(hours) + ":" + correctResponse(minutes) + ":" + correctResponse(seconds));
    }, 1000);


  });

UPDATE:

Also as a side note I realised that the countdown timer I believe is counting down every 2 second for every second. How can this be sorted for the count down timer and included in the count up timer?

The code below I have changed to include increment ++ and to include .val rather than .text but what is happening is that it starts with 00:00:00 and then it just drops down to 00:59:60 and then just stops:

var response = "00:00:00",
          parts = time.split(':'),
          hours = +parts[0],
          minutes = +parts[1],
          seconds = +parts[2],
          input = $('.responseTime');


        function correctResponse(responsenum) {
          return (responsenum<10)? ("0"+responsenum):responsenum;
        }

        var responsetimer = setInterval(function(){
            seconds++;
            if(seconds == +59) {
                seconds = 00;
                minutes++;

                if(minutes == +59) {
                    minutes = 00;
                    hours++;

                      return;

                }
            }
            input.val(correctResponse(hours) + ":" + correctResponse(minutes) + ":" + correctResponse(seconds));
        }, 1000);


      }); 

Upvotes: 3

Views: 5286

Answers (5)

Naren Yellavula
Naren Yellavula

Reputation: 7693

I added Mariusnn solution and Oerd suggestion to JSFiddle with changing val to text in Jquery.

HTML file

<body> <h1 style="color:blue">Time</h1> <h2><span class="responseTime" style="color:indianred"></span> </h2> </body>

JS code

` var startTimer;

startTimer = function() {
var time;
time = 0;
setInterval((function() {
    var hour, min, sec, str;
    time++;
    sec = time % 60;
    min = (time - sec) / 60 % 60;
    hour = (time - sec - (min * 60)) / 3600;
    count = hour + ':' + ('0' + min).slice(-2) + ':' + ('0' + sec).slice(-2);
    $('.responseTime').text(count);
    }), 1000);
   };

$( document ).ready(function() {
    startTimer();
});

`

JS fiddle solution is here.

https://jsfiddle.net/hzLf3e38/4/

Upvotes: 0

fdyahk
fdyahk

Reputation: 45

Count up try this

var millis = <?php echo $dbSessionDurationTime; ?> ( diff in seconds )

function displaytimer(){
    var hours = Math.floor(millis / 36e5),
        mins = Math.floor((millis % 36e5) / 6e4),
        secs = Math.floor((millis % 6e4) / 1000);
        //Here, the DOM that the timer will appear using jQuery
        $('.count').html(hours+':'+mins+':'+secs);  
}

setInterval(function(){
    millis += 1000;
    displaytimer();
}, 1000);

Upvotes: 0

Sergiu
Sergiu

Reputation: 311

You could easily modify the current countdown timer like here: http://jsfiddle.net/Sergiu/CDpeJ/3

var timer = setInterval(function(){
    seconds++;
    if(seconds == 60) {
        seconds = 00;
        minutes++;

        if(minutes == 60) {
            minutes = 00;
            hours++;
        }
    }
    var newTime = hours + ":" + minutes + ":" + seconds;
    if(!newTime.match(/^(20|21|22|23|[01]\d|\d)(([:.][0-5]\d){1,2})$/)) newTime = "finished";
    $('#timeInput').val(newTime);
}, 1000);

Upvotes: 2

mariusnn
mariusnn

Reputation: 1897

This is how I would have implemented such a timer:

function startTimer() {
    var time = 0
    setInterval(function(){
        time++
        var sec = time % 60
        var min = (time-sec)/60 % 60
        var hour = (time-sec-min*60)/3600
        var str= hour+':'+("0"+min).slice(-2)+':'+("0"+sec).slice(-2)
        $('.responseTime').val(str)
    },1000);
}

With an input with class responseTime to display the timer. (Why not use id btw?)

Start whenever appropriate calling startTimer() (in your example using document.onload=startTimer)

If you want to start from another time than 0, set time to the appropriate number of seconds. For a countdown, replace time++ with time-- (probably adding some logistics for time==0)

Upvotes: 2

Oerd
Oerd

Reputation: 2313

In jQuery, use the val('value') function to change/set the value of an input field.

Change input.text(...) to input.val(...)

Also:

  1. After incrementing seconds use seconds = seconds % 60; to bring them back to 0.
  2. Also, consider using data-attributes for passing values to javascript.

Upvotes: 2

Related Questions