Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery datepicker not working on created element

I have very simple datepicker setup:

this in <head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" media="screen,projection,tv" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
<script>
    $(function() {
        $('input.date').datepicker();

        $('button').on('click', function() {
            $('#orig').clone()
                .attr('id', 'else')
                .datepicker()
                .appendTo('body');
        });
    });
</script>

And this in <body>

<input type="date" id="orig" class="date">
<button>duplicate</button>

When input is cloned datepicker is not initialized on it. See on http://jsfiddle.net/aMPB2/

What is wrong with it?

like image 246
Matúš Matula Avatar asked Dec 29 '25 07:12

Matúš Matula


1 Answers

datepicker adds a marker class "hasDatepicker" to the element. You have to remove it from the clone:

Updated Fiddle

$(function() {
    $('input.date').datepicker();

    $('button').on('click', function() {
        var x = $('#orig').clone()
        .attr('id', 'else')
        .removeClass("hasDatepicker")    // <=== New line
        .appendTo('body')
        .datepicker();
    });
});
like image 118
T.J. Crowder Avatar answered Dec 30 '25 20:12

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!