Skip to content
Advertisement

Add value from textbox to counter

I’m learning javascript and I want to create a simple clock. I want for user to be able to change minutes by entering a number in textbox and pressing a button, so when that number is displayed and when the seconds are counted to 60, that displayed number increase by 1, my code won’t work, help pls:

var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");

function incrementSeconds() {
  seconds += 1;
  if (seconds === 60) {
    return seconds = 0;
  }
  el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);

dugme.addEventListener("click", function() {
  var minutes = parseInt(document.querySelector("#value").value);
  el2.innerText = minutes;
})

function incrementMinutes() {
  minutes2 += 1;
  if (minutes2 === 60) {
    return minutes2 = 0;
  }
  rezultat = (seconds + minutes2 + minutes);
  el2.innerText = rezultat;
}

var cancel = setInterval(incrementMinutes, 60000);
<form>
  <input type="text" id="value">
  <button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>

Advertisement

Answer

You have a few problems in your code. The main mistake is that your variable minutes is not defined in the function incrementMinutes() where you are trying to use it. You have to calculate it again.

Other improvements that you can make are:

  • Remove the return in your incrementSeconds and incrementMinutes function
  • Have only 1 setInterval, and call incrementMinutes when seconds reach 60.

You can see a snippet here below:

var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");

function incrementSeconds() {
  seconds += 1;
  if (seconds === 60) {
    seconds = 0;
    incrementMinutes();
  }
  el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);

dugme.addEventListener("click", function() {
  var minutes = parseInt(document.querySelector("#value").value);
  el2.innerText = minutes;
})

function incrementMinutes() {
  minutes2 += 1;
  if (minutes2 === 60) {
    minutes2 = 0;
  }
  rezultat = (minutes2 + parseInt(document.querySelector("#value").value));
  el2.innerText = rezultat;
}
<form>
  <input type="text" id="value">
  <button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement