javascriptjqueryhtml.textboxfor

Is there a better way to update html text box string format to HH:MM:SS using jQuery


Alright, after digging through several sites...I am sure there is a better way to get the result I am looking for. Users are entering data in a text box on an HTML form and I want the format to change from 152000 (HHMMSS) to 15:20:00 (HH:MM:SS)

I was able to Frankenstein the jQuery below and it does work but I'm sure there is a better way to achieve the same result. I know I could handle the data after submission but would prefer to use jQuery to update it as they type. From what I read, I could use some type of time format but everything was focused on time as a date and I just need this to be a string that adds a colon after every two digits and limits the length to 8. Any thoughts?

    $('#amount').keypress(function() {

// limits the charachters allowed
  var regex = new RegExp("^[0-9:]");
  var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
  if (!regex.test(key)) {
      event.preventDefault();
      return false;
   }
   
    //adds a colon after 2 digits typed
    if(this.value.length == 2){
        this.value = this.value+':';
     }
     
     //adds a colon after 5 character
    if(this.value.length == 5){
        this.value = this.value+':';
     }
     
     //limit to 8 total characters
     if(this.value.length > 7) {
            
        return false;
     
     }
});

Solution

  • $('#amount').keypress(function() {
      let $input = $(this);
      let value = $input.val();
      let update = value.replace(/(\d{2})(\d{2})(\d{2})/, '$1:$2:$3'); 
      // 120000 --> 12:00:00
      $input.val(update)
    })