Issue
This Content is from Stack Overflow. Question asked by Barış Aydoğdu
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 class="form-control " type="time" step="3600" asp-for="StartTime2" />
Solution
Okay, there are three ways of doing what you want to achieve.
1) Select box
Use 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 class="form-control" 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 class="form-control " 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 make the browser receive a time without minutes more than what you have already done and you cannot prevent it with pure HTML as far as I know.
This Question was asked in StackOverflow by Barış Aydoğdu and Answered by Merlin the Immortal It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.