I'm writing an alarm web app. I have two number inputs, one for the hours, one for the minutes. Thus, when I use my keyboard arrows, they go from 0 to 23/59. Is there an HTML native way to make them go from 00 (01,02, et.) to 23/59 instead ?
I'm only worried about the UI aspects as my JS manages the missing 0 anyway.
EDIT - As requested :
What I have :
What I want :
Instead of going from 0,1,2 to 59, I'd like to automatically have a leading 0 when the number is smaller than 10 (00,01,02 to 59).
I use this to just prepend zeros as needed:
<script>
function leadingZeros(input) {
if(!isNaN(input.value) && input.value.length === 1) {
input.value = '0' + input.value;
}
}
</script>
And I just call that on the input's various events how ever works best for me, for instance:
<input type="number"
value="00"
onchange="leadingZeros(this)"
onkeyup="leadingZeros(this)"
onclick="leadingZeros(this)" />
It's not an ideal solution, mainly because there's a slight visual change as the user changes the number and the zero is prepended, but it works for me :)
Edit: Forgot to mention, I appreciate the answer asked for a native solution without javascript, but I wanted to provide something for people landing here through a Google search.
I'm afraid there is not native HTML way to do that unless using a Select tag. If you are using a text input you have to add the leading 0 on the 10 first values by javascript.
The correct, modern solution to OP's problem would be to use a input with type=time and then they don't have to worry about leading zeros or any of this other stuffs.
Adding on to some of the other answers that suggest using an event listener. I've tested this with jquery in chrome and it seems to work well with the padding without the slight flashing side effect.
<input type="number" id="input-element-id" value="00">
<script>
$('#input-element-id').on('input', function() {
const value = $(this).prop('value')
$(this).prop('value', value.padStart(2, '0'))
})
</script>
Related
Ok so I don't know the first thing about knockout.js and that may be my issue.
I am maintaining an ASP.NET application and I was tasked with changing an html
file in the solution that uses knockout.js. Here is the line of code that is having an issue:
<input type="number" class="form-control" data-bind="value: Quantity, uniqueId: Quantity, uniqueMod: 'measure-quantity', enable: IsNotListMeasureIndividually() && !IsNotInstalled()" />
This input tag is allowing the user to enter a negative number and we dont want to allow that. So what I tried was to add min="1" to the tag. The result was it got ignored then moved on to the next set of lines of code
then blew up.
Is the reason that the min is not working because this is not just a simple input tag and includes knockout references in the data-bind?
If so, how can I go about putting in the desired validation to
only accept positive numbers? Please help and remember I know nothing about knockout. Thank you!!
Try Something like this. Use javascript to ignore the keypress of the negative symbol. I don't think that all browsers support the number type Of course you will need the correct handle to assign the keydown event to the right input box.
document.getElementByTagName('input')[0].addEventListener('keydown',function(e){
if ( event.which == 109 || event.which == 173 ) {
event.preventDefault();
}
});
jsfiddle
This combined with the min="0" attribute will prevent the number block from allowing negative numbers.
Although I'm pretty sure this was working yesterday or the day before, <input type="number" min="0" max="50" step="10" value="0" />, for example, no longer works in IE10. I've tested my browser with http://ie.microsoft.com/testdrive/HTML5/Forms/Default.html and it's just not working anymore. Anyone else having this issue? Or, did it never work?
Internet Explorer 10 supports the number input. This is evident from a cursory examination of their documentation, as well as an attempt to use it within the browser itself. For example, attempting to place a letter in a number input will result in the value being cleared when the control loses focus.
You can also feature-detect support for number by programmatically doing the aforementioned test:
// Create the element
var element = document.createElement( "input" );
// Give it the number property and invalid contents
element.type = "number";
element.value = "qwerty";
// Value should be empty
alert( element.value ? "Not Supported" : "Supported" );
Run this test: http://jsfiddle.net/VAZwT/
It may very well be that you're equating progressively-enhanced UI (the spinners) with support for the control itself. I've seen this confuse a few people already. Some browsers augment supplement the number input with additional controls, but this is not (to my knowledge) a requirement for support.
A few simple tests for min, max, and step on jsfiddle: http://jsfiddle.net/sDVK4/show/
Please prefer the answer below from Sampson as it's more appropriate
IE doesn't have support for input type="number" but you can use a polyfill to make it work.
Here is the solution : http://html5please.com/#number
IE10 does not have Number support. Source: Can I use ... yet?
Just verified on our Windows 8 test machine, there is no number spinner on their test drive site in IE10.
Microsoft has validation bugs/errors still with input type=number, this is in IE11 as well.
https://connect.microsoft.com/IE/feedback/details/850187/html5-constraint-validation-is-broken-in-ie11-for-input-type-number
Just as I was starting to like Internet Explorer again... Hopefully they can fix this in IE12, fingers crossed
Here's the solution I developed, it works pretty well I think, hope it helps someone 😁
function handleKeyPress(e) {
let newValue = e.target.value + e.key;
if (
// It is not a number nor a control key?
isNaN(newValue) &&
e.which != 8 && // backspace
e.which != 17 && // ctrl
newValue[0] != '-' || // minus
// It is not a negative value?
newValue[0] == '-' &&
isNaN(newValue.slice(1)))
e.preventDefault(); // Then don't write it!
}
Insert a number:
<input onKeyPress="handleKeyPress(event)"/>
IE doesn't have support for input type="number" but you can use jQueryUI Spinner widget. It is very simple to use and it has many API's that friendly for developers.
Demo of jQuery-UI Spinner:
https://jqueryui.com/spinner/
API of jQuery-UI Spinner
https://api.jqueryui.com/spinner/#event-change
Although I'm pretty sure this was working yesterday or the day before, <input type="number" min="0" max="50" step="10" value="0" />, for example, no longer works in IE10. I've tested my browser with http://ie.microsoft.com/testdrive/HTML5/Forms/Default.html and it's just not working anymore. Anyone else having this issue? Or, did it never work?
Internet Explorer 10 supports the number input. This is evident from a cursory examination of their documentation, as well as an attempt to use it within the browser itself. For example, attempting to place a letter in a number input will result in the value being cleared when the control loses focus.
You can also feature-detect support for number by programmatically doing the aforementioned test:
// Create the element
var element = document.createElement( "input" );
// Give it the number property and invalid contents
element.type = "number";
element.value = "qwerty";
// Value should be empty
alert( element.value ? "Not Supported" : "Supported" );
Run this test: http://jsfiddle.net/VAZwT/
It may very well be that you're equating progressively-enhanced UI (the spinners) with support for the control itself. I've seen this confuse a few people already. Some browsers augment supplement the number input with additional controls, but this is not (to my knowledge) a requirement for support.
A few simple tests for min, max, and step on jsfiddle: http://jsfiddle.net/sDVK4/show/
Please prefer the answer below from Sampson as it's more appropriate
IE doesn't have support for input type="number" but you can use a polyfill to make it work.
Here is the solution : http://html5please.com/#number
IE10 does not have Number support. Source: Can I use ... yet?
Just verified on our Windows 8 test machine, there is no number spinner on their test drive site in IE10.
Microsoft has validation bugs/errors still with input type=number, this is in IE11 as well.
https://connect.microsoft.com/IE/feedback/details/850187/html5-constraint-validation-is-broken-in-ie11-for-input-type-number
Just as I was starting to like Internet Explorer again... Hopefully they can fix this in IE12, fingers crossed
Here's the solution I developed, it works pretty well I think, hope it helps someone 😁
function handleKeyPress(e) {
let newValue = e.target.value + e.key;
if (
// It is not a number nor a control key?
isNaN(newValue) &&
e.which != 8 && // backspace
e.which != 17 && // ctrl
newValue[0] != '-' || // minus
// It is not a negative value?
newValue[0] == '-' &&
isNaN(newValue.slice(1)))
e.preventDefault(); // Then don't write it!
}
Insert a number:
<input onKeyPress="handleKeyPress(event)"/>
IE doesn't have support for input type="number" but you can use jQueryUI Spinner widget. It is very simple to use and it has many API's that friendly for developers.
Demo of jQuery-UI Spinner:
https://jqueryui.com/spinner/
API of jQuery-UI Spinner
https://api.jqueryui.com/spinner/#event-change
In the last update of Chrome ("23.0.1271.64 m" in my case), it seems that input=time now includes seconds that are inactive and not clickable. This doesn't look nice in our site so I want to know if someone have found a way to remove seconds.
Unfortunately jsfiddle is down and I can't post an example there, but I post it here so people can read it anyway.
<html>
<head></head>
<body>
<input type="time" value="00:44" name="tiiiiden"/>
</body>
</html>
Since seconds is only "lying there" and are not editable, it's possible that this is a bug and it will be fixed pretty soon.
I know this is a very old question, but I just found the solution.
You must change your step to 60. If you leave your step default (1), it will have to increase one second, so it must show seconds at the field.
If you set your step to 60, it will increase 1 minute at a time, so it doesn't need to show the seconds.
#hend's solution of setting step to 60 works on an empty input, but if you load your form with values prepopulated, you'll find that seconds may reappear in a disabled state.
You can mask them and the dangling colon with the following CSS:
::-webkit-datetime-edit-second-field {
background: $color-white;
color: transparent;
margin-left: -3px;
position: absolute;
width: 1px;
}
Which yields the following:
Chrome 23 stable on OSX and Linux omits the seconds fields if it is unnecessary, and Chrome 24 beta on Windows also omits it. I recommend you to wait for Chrome 24 stable release.
I could not find any change/release notes for 23.0.1271.64 m that relates to any changes of the form input types but according to the latest working draft of the HTML5 markup documentation by W3C the input type="time" element does not support any other time format than "a valid partial-time as defined in RFC 3339", and that is hh:mm:ss.ff and hh:mm:ss.
As there are no attribute to specify your own date/time format on neither one of the date/time input elements you are stuck with the defined format(s).
From input type=time – time input control
Value: A valid partial-time as defined in [RFC 3339].
Examples:
23:20:50.52
17:39:57
From RFC 3339
time-secfrac = "." 1*DIGIT
partial-time = time-hour ":" time-minute ":" time-second [time-secfrac]
Finally, I am including a screenshot of how Chrome 23.0.1271.64 m renders the different time formats (on my machine);
<input type="time" value="23:20:50.52" />
<input type="time" value="17:39:57" />
<input type="time" value="13:37" />
<input type="time" value="" />
The markup is also available at jsFiddle.
Having the same problem. I used a fixed width with white-space: nowrap and overflow: hidden to hide the seconds, but when the input is focused the problem remains.
I had the same issue, if you are using a pre populated date to fill your input, just use this :
var myDate = new Date();
myDate.setSeconds(0);
myDate.setMilliseconds(0);
With the input tag like this:
<input type="datetime-local" step="60"/>
I personaly use angular but anything should work since Date is Javascript.
Android Chrome and Webbrowser still have that problem, so I made a smartphone-specific work-around using angularjs:
http://jsfiddle.net/Rvjuf/12/
How it works:
There are 2 elements that handle this:
<span>{{ timeDisplay }}</span>
<input type="time" ng-model="time">
In the link code, style the elements (can do that in CSS file as well), and bind to the click even of the span:
scope.inputElement.css({
position: "absolute",
"z-index": "-10000",
opacity: 0
});
scope.displayElement.css({
width: "200px",
height: "20px",
background: "blue",
color: "white",
});
scope.displayElement.bind("click", function(event) {
scope.inputElement[0].focus();
scope.inputElement[0].click();
});
Then, register a change listener for the time value and update the timeDisplay variable:
$scope.$watch('time', function(nv, ov) {
var parts = nv.split(" ")[0].split(":");
var hours = parts[0];
var minutes = parts[1];
$scope.timeDisplay = $filter('date')(new Date(2014, 03, 06, hours, minutes, 0), "H:mm");
});
So, when the user taps on the span, the input either gets focussed or clicked (iOS and ANDROID make some difference there), causing the native time picker UI to come up.
You can add a pattern attribute on your time input.
<input
type="time"
name="time"
pattern="[0-9]{2}:[0-9]{2}"
/>
We're using moment.js to fix this. You can round down the seconds to avoid the milis in a prePopulated input time by setting on controller with:
const localDate = moment(data.date).startOf('minute').toDate();
I hope it helps ;)
If you're using a Mac and step="60" still does not work, it could be your time preferences.
Chrome was using the "Short" time. I removed the seconds and milliseconds from the Short time, restarted Chrome and that solved it for me.
Found in: Language & Region > Advanced... > Times
Can I replace the maxlength attribute with something in CSS?
<input type='text' id="phone_extension" maxlength="4" />
No.
maxlength is for behavior.
CSS is for styling.
That is why.
No. This needs to be done in the HTML. You could set the value with Javascript if you need to though.
You can use jQuery like:
$("input").attr("maxlength", 4)
Here is a demo: http://jsfiddle.net/TmsXG/13/
I don't think you can, and CSS is supposed to describe how the page looks not what it does, so even if you could, it's not really how you should be using it.
Perhaps you should think about using JQuery to apply common functionality to your form components?
Not with CSS, no.
Not with CSS, but you can emulate and extend / customize the desired behavior with JavaScript.
As others have answered, there is no current way to add maxlength directly to a CSS class.
However, this creative solution can achieve what you are looking for.
I have the jQuery in a file named maxLengths.js which I reference in site (site.master for ASP)
run the snippet to see it in action, works well.
jquery, css, html:
$(function () {
$(".maxLenAddress1").keypress(function (event) {
if ($(this).val().length == 5) { /* obv 5 is too small for an address field, just want to use as an example though */
return false;
} else {
return true;
}
});
});
.maxLenAddress1{} /* this is here mostly for intellisense usage, but can be altered if you like */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="maxLenAddress1" />
The advantage of using this: if it is decided the max length for this type of field needs to be pushed out or in across your entire application you can change it in one spot. Comes in handy for field lengths for things like customer codes, full name fields, email fields, any field common across your application.
Use $("input").attr("maxlength", 4)
if you're using jQuery version < 1.6
and $("input").prop("maxLength", 4)
if you are using jQuery version 1.6+.