Skip to content
This repository has been archived by the owner on Aug 20, 2022. It is now read-only.

Attach .datepicker to dynamically created input #134

Open
eriktobben opened this issue Mar 30, 2018 · 3 comments
Open

Attach .datepicker to dynamically created input #134

eriktobben opened this issue Mar 30, 2018 · 3 comments

Comments

@eriktobben
Copy link

Hi,

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

@pixelcommerce
Copy link

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

@eriktobben
Copy link
Author

eriktobben commented Mar 30, 2018

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.

@Gataquadrada
Copy link

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants