Bootprap timepicker only selects the first timepicker element
I have a form where a user can add dynamic bootprap timepicker fields.
I am using Bootstrap timepicker ( https://github.com/eternicode/bootstrap-datepicker ) for timepicker input fields that will be dynamically generated
The problem is that when clicking on any datepicker element (except the first one), all changes only happen to the first one.
Here is the JSFIDDLE
HTML part of my code:
<div class="row multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<div class="form-group col-xs-12 col-sm-4">
<div class="input-group">
<input type="text" name="ticket-price" maxlength="5" class="form-control" placeholder="FREE" >
<span class="input-group-btn">
<button class="btn btn-default add-field" type="button">+</button>
</span>
<span class="input-group-btn">
<button class="btn btn-default remove-field" type="button">-</button>
</span>
</div>
</div>
<div class="row">
<div class="form-group col-xs-6 col-sm-3">
<label>Start Date</label>
<input type="text" name="tstart-date" class="form-control tstart-date-picker" placeholder="">
</div>
</div>
</div>
</div>
</div>
source to share
The problem is you are cloning DOM elements with event handlers attached by jQuery. This causes problems when trying to pick a date on a new input, because the events associated with the datepicker are somehow mixed with the original on the first input.
The fix is ββpretty simple: clone with no argument true
, and also use the click delegated event to add new lines. The rest does not change:
$(this).on('click', '.add-field', function (e) {
$('.multi-field:first-child', $wrapper).clone().appendTo($wrapper);
$('.multi-field:last-child').find('input[name="tstart-date"]').val('');
$('.multi-field:last .tstart-date-picker').datepicker({
autoclose: true,
format: 'dd-M-yyyy',
todayHighlight: true,
});
});
source to share