Search code examples
javascriptjqueryroundingtimepickertime-select

How to prevent jQuery bootstrap ClockPicker to get minutes that are not divisible by 5


I am using jQuery bootstrap ClockPicker and need to get only times that their minutes are divisible by 5. For example if user selects 13:08, the ClockPicker should select 13:05.

Is there a way to override clockpicker to round down selected times minutes?


Solution

  • I didn't found a way to do this with the API. So I wrote one using afterDone callback.

    I parse the input's value and make the change to get the new minutes value.

    var clockpicker = $('.clockpicker').clockpicker({
      afterDone: function() {
        clockpicker.val(round());
      }
    }).find('input');
    
    function round() {
      var time = clockpicker.val(),
          arr = time.split(':'),
          hour = arr[0],
          min = arr[1],
          newMin = (Math.floor(parseInt(min) / 5)) * 5;
    
      return hour + ':' + (newMin > 9 ? '' : '0') + newMin;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://weareoutman.github.io/clockpicker/dist/bootstrap-clockpicker.min.css" rel="stylesheet" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://weareoutman.github.io/clockpicker/dist/bootstrap-clockpicker.min.js"></script>
    
    <div class="input-group clockpicker col-xs-6">
      <input type="text" class="form-control" value="09:30">
      <span class="input-group-addon">
        <span class="glyphicon glyphicon-time"></span>
      </span>
    </div>

    http://jsbin.com/lopufu/edit?html,js