manraj82
manraj82

Reputation: 6295

jQuery Plugin not working for elements added dynamically

How do I get a jQuery Plugin working for elements added dynamically? I'm trying to add few date pickers to the DIV datesList each time you cick the Add button. The plugin doesnt work for the textboxes that are added dynamically. Can some one please advice?

Thank You

HTML

<div class="datesList">
    <div class="date">
        <input type="text" class="date-picker"/>
    </div>
</div>

<div class="addDate">
    Add Date
</div>

JS

$(".date-picker").datepicker();

$(".addDate").click(function(){
   var dList = $(".datesList");
   dList.find(".date").first().clone(false).appendTo(dList);
});

Upvotes: 0

Views: 212

Answers (4)

sayannayas
sayannayas

Reputation: 774

this works but you may not like the way i did it

$(".date-picker").datepicker();

$(document).on('click', '.addDate', function() {
    var dList = $(".datesList");
    var newinput = $('<input type="text" />').attr('class', 'date-picker');
    dList.append(newinput);
    var newdatepickr = $(".date-picker").datepicker();
});​

http://jsfiddle.net/2pFAd/

Upvotes: 0

rajesh kakawat
rajesh kakawat

Reputation: 10896

try this

 $(".date-picker").datepicker();

 $(".addDate").click(function(){
   var dList = $(".datesList");
   dList.find(".date").first().clone(false).appendTo(dList);
   $(".date-picker").datepicker();
});

Upvotes: 1

devnull69
devnull69

Reputation: 16544

If this is the jQuery UI datepicker you can simply call .datepicker('refresh') after each update.

Upvotes: -1

kapantzak
kapantzak

Reputation: 11750

Use jquery on() http://api.jquery.com/on/ like so:

$(document).on('click', '.addDate', function() {
     YOUR FUNCTION
});

For better perfomance instead of $(document), use the closest DOM element that is loaded for the first time

Upvotes: 1

Related Questions