datepicker
datepicker copied to clipboard
Attach .datepicker to dynamically created input
Hi,
How can I attach the datepicker to input elements that have been dynamically inserted to the site?
Hey @eriktobben, how are you inserting the input dynamically? Can you show some code?
Hi @pixelcommerce. Here is the code:
jQuery:
$('.new-line').on('click', function () {
var source = document.getElementById("row-template").innerHTML;
var template = Handlebars.compile(source);
var html = template();
$('.productcontainer').append(html);
});
Datepicker:
$('.date').datepicker({
format: 'dd.mm.yyyy'
});
HTML Handlebars template (the same code as rendered on page load):
<div class="col-md-2">
<div class="form-group">
<input type="text" class="form-control date" name="delivery_date[]" autocomplete="off" />
</div>
</div>
So the datepicker is working great on the first row that in rendered on page load, but every new row that is created with JS does not work. I assume that it is because the DOM is changed and it does not pick up on that.
Why are you using native JS while inside jQuery like that?
Just go for:
$( '.productcontainer' ).append( $( '#row-template' ).html() );
And then:
$( '.date' ).datepicker({
format: 'dd.mm.yyyy'
});
I assume you're trying to create an infinite record table for adding/updating multiple rows. I'd recommend .clone or template literals for that matter.