Search code examples
jquerytimepicker

How can I set the time from one input to another by one hour later?


I have a form and when I choose the starttime, I want to set the endtime by one hour later.

I tried to solve it this way:

$('#timepicker2').val($('#timepicker1').val());

But nothing happened:

enter image description here

Time format is "HH:mm"

<div class="form-group">
    <label for="exampleInputEmail1"> <?php echo lang('date'); ?></label>

    <input type="text" class="form-control default-date-picker" readonly="" name="date"
           id="exampleInputEmail1" value='' placeholder="">

</div>
<div class="form-group col-md-12">
    <label for="timepicker1"> <?php echo lang('start_time'); ?></label>
    <div class="col-md-4">
        <div class="input-group bootstrap-timepicker timepicker">
            <input id="timepicker1" type="text" class="form-control input-small" name="s_time">
            <span class="btn btn-default input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
        </div>
    </div>
</div>

<div class="form-group col-md-12">
    <label for="timepicker2"> <?php echo lang('end_time'); ?></label>
    <div class="col-md-4">
        <div class="input-group bootstrap-timepicker timepicker">
            <input id="timepicker2" type="text" class="form-control input-small" name="e_time">
            <span class="btn btn-default input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
        </div>
    </div>
</div>

Solution

  • Here's an Plunker example from what it looks like you're trying to do.

    var time1 = document.querySelector('#time1'),
        time2 = document.querySelector('#time2');
    
    time1.addEventListener('change', function(e){
      time2.value = parseInt(time1.value) + 1;
    });
    

    Update Based on new Question

    var time1 = document.querySelector('#time1'),
        time2 = document.querySelector('#time2');
    
    time1.value = '10:00';
    
    time1.addEventListener('change', function(e){
      var t1 = time1.value.split(':').map(Number);
    
      if(t1[1] < 10) t1[1] = '0' + t1[1];
    
      t1[0] = (t1[0] + 1)%13;
    
      if(t1[0] === 0) t1[0] = 1;
    
      time2.value = t1.join(':');
    }); 
    

    That's just a quick hacky solution, it's just to give you an idea of what you can do. There's obviously no validation.

    You should probably use a date object new Date() it will accept a date string as the first parameter and parse it into a date. To add an hour to your date

    var d = new Date();
    d.setHours( d.getHours() + 1);