I have the following requirement: in the temporary field of the form, add a colon automatically on the fly, if not manually, in this format hh: mm: ss
I have the code below and it works fine for auto-completion, but if the user's user colon manually adds two colons, for example hh :: m: ss
Can someone help with this problem?
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 must add an additional check before smoothing with the chiliNUT answer , otherwise select everything and pressing the delete / return button does not work in the Chrome browser.
$('#runTime').on('keydown', function(e) {
if(e.keyCode != 8 && (this.value.length === 2 || this.value.length === 5)) {
this.value += ":";
}
if(this.value.endsWith("::")) {
this.value=this.value.replace(/:+/g,":");
}
});
Mohan source
share