Home > Software engineering >  Input Type Time Display Just Hour
Input Type Time Display Just Hour

Time:09-18

I want to allow pick just hours. I dont wanna display and allow miniutes. For example, User must pick 14.00,16.00 etc. I tried step attribute but ıt is still showing and allowing pick miniutes. How can user just pick full hours?

 <input  type="time" step="3600" asp-for="StartTime2" />

enter image description here

CodePudding user response:

Okay, there are three ways of doing what you want to achieve.

#1) Select box# Use a code similar to this:

<select>
  <option value="0">00:00</option>
  <option value="1">01:00</option>
  <option value="2">02:00</option>
  <option value="3">03:00</option>
  <option value="4">04:00</option>
  <option value="5">05:00</option>
  <option value="6">06:00</option>
  <option value="7">07:00</option>
  <option value="8">08:00</option>
  <option value="9">09:00</option>
  <option value="10">10:00</option>
  <option value="11">11:00</option>
  <option value="12">12:00</option>
  <option value="13">13:00</option>
  <option value="14">14:00</option>
  <option value="15">15:00</option>
  <option value="16">16:00</option>
  <option value="17">17:00</option>
  <option value="18">18:00</option>
  <option value="19">19:00</option>
  <option value="20">20:00</option>
  <option value="21">21:00</option>
  <option value="22">22:00</option>
  <option value="23">23:00</option>
</select>

Which to be honest isn't the best!

#2) Using JS to reset the minutes; Recommended#

function resetMin(e) {
  e.addEventListener("change", function() {
    e.value = e.value.split(":")[0]   ":00";
  });
}
resetMin(document.getElementsByClassName("form-control")[0]);
<input  type="time" step="3600" asp-for="StartTime2" />

Which I recommend

#3)Having a number input box#

function resetMin(e) {
  e.addEventListener("change", function() {
    e.value = parseInt(e.value % 24);
  })
}
resetMin(document.getElementsByClassName("form-control")[0]);
<input  type="number" step="1" min="0" max="23" asp-for="StartTime2" />

This also does the trick but is not the best

But I'm afraid you cannot prevent the browser to not receive a time without minutes more than what you have already done and you cannot prevent it with pure HTML as much as I know

CodePudding user response:

In this, user can only input the value between 1 and 24

<input type="number" id="yourId" min="1" max="24">

  • Related