JSFiddle - React, Tailwind, and code Playground

by Taleeb Anwar

HTML

<input type='text' id='txt' />

JavaScript

$('#txt').keydown(function(event) {
  if (event.which == 58 || event.which == 186) {
    if ($('#txt').val().replace(':', '') < 10 && $('#txt').val().replace(':', '') > 0) {

      $('#txt').val("0" + $('#txt').val().replace(/:/g, '') + ":");
      event.preventDefault();
    }
  }
  //
  if (event.which == 8) {

    if ($('#txt').val().length == 3) {
      console.log('here');
      $('#txt').val($('#txt').val().replace(':', ''));
    }
  }
  if (event.which != 8 && event.which != 46 && isNaN(String.fromCharCode(event.which))) {
    event.preventDefault(); //stop character from entering input
  }

  if ($('#txt').val() == 2) {
    if (event.which != 8 && event.which != 46 && event.which != 96 && event.which != 97 && event.which != 98 && event.which != 99 && event.which != 100 && event.which != 48 && event.which != 49 && event.which != 50 && event.which != 51 && event.which != 52) {
      console.log(event.which);
      event.preventDefault();
    }
  } else if ($('#txt').val() >2 && event.which != 8 && event.which != 46) {
    event.preventDefault();
  }
});
$('#txt').keyup(function() {
  if ($('#txt').val().length == 2) {
		var value = parseInt($('#txt').val());
		console.log(value);
		if(value == 24){
			value = '00';
		}
		else if(value>21){
		 value = value-12;
		}
		else if(value>12){
		  value = value-12;
			value = "0" + "" + value;
		}
		else if(value<10){
			value = "0" + "" + value;
		}
    $('#txt').val(value + ":");
  }
  if ($('#txt').val().replace(/:/g, '').length < 2) {
    $('#txt').val($('#txt').val().replace(/:/g, ''));
  }
	
});