I have following requirement, in time field of form should add colon automatically on fly if not key manually in this format hh:mm:ss
I have below code and it works fine for fulling automatic, but if user key colon manually it is adding two colon like hh::m:ss
Can someone help with this issue?
JSP:
<b:form-group label="${runtime}" labelFor="runtime" cssLabel="col-sm-2" cssBody="col-sm-2" cssClass="required">
<form:input path="runTime" cssClass="form-control" required="required" maxlength="8"/>
<form:errors path="runTime" cssClass="validate-error"/>
</b:form-group>
JS:
$('#runTime').on('keydown', function(e) {
if(e.keyCode != 8 && (this.value.length === 2 || this.value.length === 5)) {
this.value += ":";
}
});
Update Answer
We have to add extra check before collapse with chiliNUT answer, else select all and hitting delete/backspace button is not working in chrome browser.
$('#runTime').on('keydown', function(e) {
//your code
if(e.keyCode != 8 && (this.value.length === 2 || this.value.length === 5)) {
this.value += ":";
}
//collapse double colons
if(this.value.endsWith("::")) {
this.value=this.value.replace(/:+/g,":");
}
});
Collapse double colons after keydown
$('#runTime').on('keydown', function(e) {
//your code
if(e.keyCode != 8 && (this.value.length === 2 || this.value.length === 5)) {
this.value += ":";
}
//collapse double colons
this.value=this.value.replace(/:+/g,":");
});
That last line will look at the string, then take any instance of 1 or more colons (contiguous colons? :-)) and turn it into a single colon
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With