datepicker icon indicating copy to clipboard operation
datepicker copied to clipboard

Attach .datepicker to dynamically created input

Open eriktobben opened this issue 6 years ago • 3 comments

Hi,

How can I attach the datepicker to input elements that have been dynamically inserted to the site?

eriktobben avatar Mar 30 '18 16:03 eriktobben

Hey @eriktobben, how are you inserting the input dynamically? Can you show some code?

pixelcommerce avatar Mar 30 '18 18:03 pixelcommerce

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.

eriktobben avatar Mar 30 '18 20:03 eriktobben

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.

Gataquadrada avatar Feb 03 '19 23:02 Gataquadrada