Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5: input type duration

Is there a way to use input type duration. I am trying to make a input in a way, a user to add time duration something like this 06:30:27:15 ( hh:mm:ss:ms ) and should allow only (0-23:0-59:0-59:0-59).

any help appreciated!

NOTE!: I want to implement this in Angular2+.

like image 783
The Rock Avatar asked Feb 04 '20 21:02

The Rock


1 Answers

Sadly, neither HTML inputs nor JavaScript itself support a duration data type. <input type="time"> is for a time of the day, and may display AM/PM selectors depending on your locale.

Your best bet is to work with a text input and to use JavaScript events to automatically insert : and ignore invalid inputs. Using the pattern attribute may also help. Be sure to convert the value to a number before using it from the JavaScript side of things. Here's something to get you started.

{
  let durationIn = document.getElementById("duration-input");
  let resultP = document.getElementById("output");
  
  durationIn.addEventListener("change", function (e) {
    resultP.textContent = "";
    durationIn.checkValidity();
  });
  
  durationIn.addEventListener("invalid", function (e) {
    resultP.textContent = "Invalid input";
  });
}
input:invalid:not(:focus) { background: red; }
<input id="duration-input" type="text" required pattern="[0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{2}" value="00:00:00:00" title="Write a duration in the format hh:mm:ss:ms">

<p id="output"></p>

I'm sure there are many open-source libraries which provide a ready-made widget for that.

like image 145
Domino Avatar answered Nov 17 '22 15:11

Domino