2

How can I make a text input look and act like a time input? For example if I enter the number 1244, it will be inserted into the text box like so:

enter image description here

What is the proper way to do it? I prefer the colon to always be visible (Not just when numbers are being inserted)

5
  • 1
    Just use type="time" in the input. Commented Jul 30, 2023 at 5:27
  • type="time" is inconsistent, I want something that will look and behave the same on the browsers, for example I want the user to be able to insert 24H format and not choose AM/PM. I also want to stylize the input borders to match other text inputs. But I could be wrong, and both can be done (i.e. to make the time 24H format on Chrome for example by default, and also stylize the box itself, like border color, width, padding etc. so I just wanted a simple text input which is also easy to just type in the values) Commented Jul 30, 2023 at 5:39
  • 1
    If type="time" won't work for you, you'll probably need to use JS and Regex. JS to listen for the change on the input and run a function to update the input to include the : before the last two numbers. You'll also what to use JS to set up validation on this input. Commented Jul 30, 2023 at 6:01
  • @davidleininger thank you. I prefer to always have the : there as part of the styling, and when a user enter a number, it will simply move to the correct place. Of course validation will also be done via JS/backend (but I want to be able to style it as seen above with the colon always there) Commented Jul 30, 2023 at 6:19
  • 1
    Then, I think you'd need to use two inputs and style it to look like one. Without JavaScript, you won't be able to add a : in between characters. So input-hour : input-minute. Then you'd have to wrap that with a div or something and apply your input styles there. Set the focus styles with :focus-within. Commented Jul 30, 2023 at 6:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.