1

How to save a time value in dynamically created li to input box with javascript I have a simple timer, that starts, stops, pauses, takes a time snap and resets the time snap. The timesnap in generated and displayed in the webpage inside a li. It all works fine what I am struggling with is trying to click on a displayed time snap and have the value placed in an input box so I can later save a selected value to a database. This is the script I am using to place the clicked on li item into the input box

var items = document.querySelectorAll("#list li");
      for (var i = 0; i < items.length; i++) {
        items[i].onclick = function () {
          document.getElementById("inptSnap").value = this.innerHTML;
        };
      }

This is the html

<div class="container">
      <!--               Different App            -->

      <div class="timeDisplay">00:00:00</div>

      <button id="begin">Start</button>

      <button id="hold">Pause</button>

      <button id="end">Stop</button>

      <button id="timeSnap">Time Snap</button>
      <button id="resetSnap">Reset Time Snap</button>

      <ul id="list" class="laps"></ul>

      <div>
        <input type="text" id="inptSnap" />
      </div>
    </div>

This is the full timer script with the attempted select value onclick

var begin = document.getElementById("begin");
      begin.addEventListener("click", start);

      var end = document.getElementById("end");
      end.addEventListener("click", stop);

      var hold = document.getElementById("hold");
      hold.addEventListener("click", pause);

      var timeSnap = document.getElementById("timeSnap");
      timeSnap.addEventListener("click", snap);

      var timeSnap = document.getElementById("timeSnap");
      timeSnap.addEventListener("click", pause);

      var resetSnap = document.getElementById("resetSnap");
      resetSnap.addEventListener("click", resetSnaps);

      var ms = 0,
        s = 0,
        m = 0;
      var timeCounter;
      var displayEl = document.querySelector(".timeDisplay");
      var lapsContainer = document.querySelector(".laps");

      function start() {
        if (!timeCounter) {
          timeCounter = setInterval(run, 10);
        }
      }

      function run() {
        displayEl.textContent = displayTimeCount();

        ms++;
        if (ms == 100) {
          ms = 0;
          s++;
        }
        if (s == 60) {
          s = 0;
          m++;
        }
      }

      function stop() {
        stopTimer();
        ms = 0;
        s = 0;
        m = 0;
        displayEl.textContent = displayTimeCount();
      }
      function stopTimer() {
        clearInterval(timeCounter);
        timeCounter = false;
      }

      function pause() {
        stopTimer();
      }

      function displayTimeCount() {
        return (
          (m < 10 ? "0" + m : m) +
          ":" +
          (s < 10 ? "0" + s : s) +
          ":" +
          (ms < 10 ? "0" + ms : ms)
        );
      }
      function snap() {
        if (timeCounter) {
          var li = document.createElement("li");
          li.innerText = displayTimeCount();
          lapsContainer.appendChild(li);
        }
      }

      function resetSnaps() {
        lapsContainer.innerHTML = "";
      }

      // Script to put lap into input box
      var items = document.querySelectorAll("#list li");
      for (var i = 0; i < items.length; i++) {
        items[i].onclick = function () {
          document.getElementById("inptSnap").value = this.innerHTML;
        };
      }

This is the CodePen Link

I would be very grateful for any pointers and advice, thanks

0

2 Answers 2

2

You can do somthing like that...

PS: I think that the ergonomics of your button is to be reviewed, I did a kind of revision.

const
  btStartPause = document.querySelector('#container button:nth-of-type(1)')
, btStopClear  = document.querySelector('#container button:nth-of-type(2)')
, btSnap       = document.querySelector('#container button:nth-of-type(3)')
, snapList     = document.querySelector('ol')
, inptSnap     = document.querySelector('input#inptSnap')
, chrono = ((dZTime='#container time') =>
  {
  const
      displZone  = document.querySelector(dZTime)
    , chronoZero = '00:00:00.000'
    , one_Sec    = 1000
  //, one_Min    = one_Sec * 60
  //, one_Hrs    = one_Min * 60
    , n_Dgts     = (n,t) => `${t}`.padStart(n,'0')
    ;
  let startTime   = null
    , timeElapsed = 0
    , pausedTime  = 0
    , reqRef      = null
    , reqPause    = false
    , stoped      = false
      ;
  displZone.textContent = chronoZero

  function reqLoop(timeStamp)  // timeStamp is float
    {
    startTime ??= timeStamp  // Logical nullish assignment (??=)

    if (stoped)
      {
      cancelAnimationFrame(reqRef)
      return
      }
    if (reqPause) 
      { 
      pausedTime = (timeStamp - startTime) - timeElapsed;
      }
    else
      {
      timeElapsed = ((timeStamp - startTime) - pausedTime) | 0 // get integer part of float
      let
        Tms = timeElapsed % one_Sec
      , tim = (timeElapsed - Tms) / one_Sec
      , T_s = tim % 60
      , T_m = 0
      , T_h = 0
        ;
      tim = (tim - T_s) / 60 
      T_m = tim % 60
      T_h = (tim - T_m) / 60 

      displZone.textContent = `${n_Dgts(2,T_h)}:${n_Dgts(2,T_m)}:${n_Dgts(2,T_s)}.${n_Dgts(3,Tms)}`
      }
    requestAnimationFrame( reqLoop )
    }
  const jso =
    { dispSz:      chronoZero.length
    , getVal: ()=> displZone.textContent 
    , start()      { reqRef   = requestAnimationFrame(reqLoop) }
    , pause(OnOff) { reqPause = OnOff }
    , stop()       { stoped   = true  }
    , RaZ()
      {
      startTime   = null
      timeElapsed = 0
      pausedTime  = 0
      reqRef      = null
      reqPause    = false
      stoped      = false
      displZone.textContent = chronoZero
      }
    }
  Object.freeze(jso)
  return jso
  })()
  ;
btStartPause.onclick =_=>
  {
  if (btStartPause.classList.toggle('pause') )
    {
    btStopClear.disabled = false 

    if ( btStartPause.dataset.lib !== 'continue' )
      {
      btStartPause.dataset.lib = 'continue'
      chrono.start()
      }
    else
      chrono.pause(false)
    }
  else
    {
    btStopClear.disabled = true 
    btStopClear.classList.remove('clear') 
    chrono.pause(true)
    }
  }
btStopClear.onclick =_=>
  {
  if (btStopClear.classList.toggle('clear') )
    {
    btStartPause.disabled    = true
    btStartPause.dataset.lib = 'start'
    btStartPause.classList.remove('pause')
    chrono.stop()   
    }
  else
    {
    btStartPause.disabled = false
    btStopClear .disabled = true 
    chrono.RaZ()
    }
  }
btSnap.onclick =_=>
  { 
  snapList
  .appendChild( document.createElement('li'))
  .innerHTML = chrono.getVal() 
              + '<span title="delete"> &#10006; </span>'
              + '<span title="copy"> &#x2398 </span>'
  }
snapList.onclick =({target}) =>
  {
  if (!target.matches('li > span'))
    {
    inptSnap.value = target.closest('li').textContent.substring(0, chrono.dispSz)
    inptSnap.focus()
    return
    } 

  if (target.matches('span[title=delete]'))
    {
    target.closest('li').remove()
    }

  if (target.matches('span[title=copy]'))
    {
    let origin = target.closest('li')
    copySomething ( origin.textContent.substring(0, chrono.dispSz), origin )
    }
  }
async function copySomething(toCopy, el ) 
  {
  try
    {
    await navigator.clipboard.writeText(toCopy);
    el.classList.add('copyOK')
    setTimeout(() => { el.classList.remove('copyOK')}, 1200);
    }
  catch (err) 
    {
    el.classList.add('copyBad')
    setTimeout(() => { el.classList.remove('copyBad')}, 1200);
    console.error('Failed to copy :/', err);
    }
  }
body {
  font-family : Arial, Helvetica, sans-serif;
  font-size   : 16px;
  }
time {
  display        : block;
  font-size      : 1.4rem;
  margin         : .6rem 1rem;
  letter-spacing : .2rem;
  }
ol {
  list-style : none;
  font-size  : 1.6rem;
  padding    : 0;
  margin     : 1.5rem;
  width      : 15rem;
  list-style-type: decimal;
  }
li {
  border    : 1px solid lightblue;
  padding   : .3rem .6rem;
  position  : relative;
  cursor    : pointer;
  }
li::marker {
  font-size : .9rem;
  color     : darkslategray;
  }
li span {
  float     : right;
  margin    : 0 0 0 .3em;
  font-size : 1.2rem;
  color     : darkslategray;
  }
li span[title=delete]:hover {
  color     : crimson;
  }
li span[title=copy]:hover {
  background : white;
  color      : darkblue;
  }
#container button {
  min-width      : 4.4rem;
  text-transform : capitalize;
  }
#container button:before {
  content : attr(data-lib)
  }
#container button.pause:before {
  content : 'pause'
  }
#container button.clear:before {
  content : 'clear'
  }
li:hover {
  background : lightblue;
}
li.copyOK::after,
li.copyBad::after {
  position   : absolute;
  display    : block;
  font-size  : .8rem;
  top        : 1.2rem;
  left       : 11rem;
  padding    : .1rem .2rem;
  }
li.copyOK::after {
  content    : 'copied';
  background : lightgreen;
  }
li.copyBad::after {
  left       : 1rem;
  content    : 'Failed to copy :/';
  background : lightcoral;
  }
<input type="text" id="inptSnap" >
<hr>

<div id="container">
  <time datetime="00:00:00.000">00:00:00.000</time>
  <button data-lib="start"><!-- start / continue / pause --></button>
  <button data-lib="stop" disabled><!-- stop / clear --></button>
  <button>snap</button>
</div>
<ol></ol>

for info : Fastest way to cast a float to an int in javascript?

0
2

So I understand that you need a place value kind of thing.

 var begin = document.getElementById("begin");
      begin.addEventListener("click", start);

      var end = document.getElementById("end");
      end.addEventListener("click", stop);

      var hold = document.getElementById("hold");
      hold.addEventListener("click", pause);

      var timeSnap = document.getElementById("timeSnap");
      timeSnap.addEventListener("click", snap);

      var timeSnap = document.getElementById("timeSnap");
      timeSnap.addEventListener("click", pause);

      var resetSnap = document.getElementById("resetSnap");
      resetSnap.addEventListener("click", resetSnaps);

      var ms = 0,
        s = 0,
        m = 0;
      var timeCounter;
      var displayEl = document.querySelector(".timeDisplay");
      var lapsContainer = document.querySelector(".laps");

      function start() {
        if (!timeCounter) {
          timeCounter = setInterval(run, 10);
        }
      }

      function run() {
        displayEl.textContent = displayTimeCount();

        ms++;
        if (ms == 100) {
          ms = 0;
          s++;
        }
        if (s == 60) {
          s = 0;
          m++;
        }
      }

      function stop() {
        stopTimer();
        ms = 0;
        s = 0;
        m = 0;
        displayEl.textContent = displayTimeCount();
      }
      function stopTimer() {
        clearInterval(timeCounter);
        timeCounter = false;
      }

      function pause() {
        stopTimer();
      }

      function displayTimeCount() {
        return (
          (m < 10 ? "0" + m : m) +
          ":" +
          (s < 10 ? "0" + s : s) +
          ":" +
          (ms < 10 ? "0" + ms : ms)
        );
      }
      function snap() {
        if (timeCounter) {
          var input = document.createElement("input");
          input.value = displayTimeCount();
          lapsContainer.appendChild(input);
        }
      }

      function resetSnaps() {
        lapsContainer.innerHTML = "";
      }

      // Script to put lap into input box
      var items = document.querySelectorAll("#list li");
      for (var i = 0; i < items.length; i++) {
        items[i].onclick = function () {
          document.getElementById("inptSnap").value = this.innerHTML;
        };
      }
 .timeDisplay {
        font-size: 32px;
      }
      ul li {
        list-style: none;
        font-size: 32px;
      }
      .container {
        width: 400px;
        margin: auto;
      }
<div class="container">
      <!--               Different App            -->

      <div class="timeDisplay">00:00:00</div>

      <button id="begin">Start</button>

      <button id="hold">Pause</button>

      <button id="end">Stop</button>

      <button id="timeSnap">Time Snap</button>
      <button id="resetSnap">Reset Time Snap</button>

      <ul id="list" class="laps">
        
      </ul>

      <div>
        <input type="text" id="inptSnap" />
      </div>
    </div>

3
  • 3
    a lot of code for an erroneous measurement of time... developer.mozilla.org/en-US/docs/Web/API/… Feb 18, 2022 at 13:58
  • @MisterJojo thanks for your input and the link, I will work on it Feb 18, 2022 at 14:21
  • 1
    @ash Your answer is very close to what I wanted. However, in my original code when the snaptime button is pressed the time is displayed as a list item. If the timer is restarted and the snaptime is clicked again another time is displayed in the list and so on. What I attempted is to make a selection and have the selected time placed in the input box. If you see the CodePen link you will see the list is produced but when one of the items is clicked on, the value is not placed in the input box below. Thanks very much for your help, using your example I will work on it further. Thanks Feb 18, 2022 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.