Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic colon in time field in form

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,":");
    }
});
like image 885
Mohan Avatar asked Mar 03 '17 21:03

Mohan


1 Answers

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

like image 200
chiliNUT Avatar answered Nov 10 '22 05:11

chiliNUT