Search code examples
javascriptjquerytimedivide

divide time 0900 to 09:00


If I enter 0900 in this text field then I would like it to automatically turn into 09:00

form

<form action="form.html">
  <p>
    <label>time:</label>
    <input type="text" name="time" class="time"/>
  </p>
  <span id="error" class="hide">Error in the field</span>
</form>

I Know I should use the following to at least get the value and then I have to turn that value into the value that I want:

$(document).ready(function(){
  $(".time").on("focusout",function(){
    var old_value = $(this).val();

    // The old value to the new value
    if(old_value.length < 2 || > 4){
      $("#error").show();
    } else {
      if(old_value.length == 2){
        // Then add 2 leading zero's
        // Then add a : in the middle
      } else if (old_value.length == 3){
        // Then add 1 leading zero's
        // Then add a : in the middle
      } else if (old_value.length == 4){
        // Then add a : in the middle
      }
    }
  }

Thanks in advance for the effort taken. If something isn't clear please ask me.


Solution

  • Use this as a basis to solve your problem:

    $("#your_filed_id").on("focusout", function(){
        // Do whatever checking you like here 
    });