Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to attach jQuery UI datepicker to dynamically inserted formfield?

I have a table containing a bunch of input fields, sort of like a spreadsheet. Some of the input fields use the jQuery UI datepicker. There is also a button to add a table row.

When I click the button to add a table row, it is added to the DOM correctly. But, the datepicker widget doesn't get attached to the date fields in that new row.

I suspect the answer is to use live() - or maybe on() - to call datepicker(), but I don't understand what syntax to use. The code below is already pushing the limits of my jQuery understanding. My head hurts. Help?

<script type="text/javascript">
    $(function() {
        $( ".usedatepicker" ).datepicker();
    });

    $('.rowadd').live('click',function(){
        var appendTxt = '<tr><td><input class="usedatepicker" name="something" type="text" /></td></tr>';
        $("tr:last").after(appendTxt);
    });

</script>

Note 2: I've tried this as well, with both live() and on(). It seems to work on both the original fields and the dynamically inserted ones, but sporadically (at least in Chrome). Like, it'll work for three seconds and then stop for three seconds, and then work for three seconds and...

$(function() {
    $('.usedatepicker').live('click', function(){
        $(this).datepicker({showOn:'focus'});
    });
});
like image 838
Derrick Miller Avatar asked Apr 10 '12 20:04

Derrick Miller


1 Answers

Just rebind the datepicker after adding a new row. If that fails, try the "refresh" method.

$('.rowadd').live('click',function(){
        var appendTxt = '<tr><td><input class="usedatepicker" name="something" type="text" /></td></tr>';
        $("tr:last").after(appendTxt);
        $(".usedatepicker").datepicker(); // or 
        $(".usedatepicker").datepicker("refresh"); 
    });
like image 65
Marko Avatar answered Oct 23 '22 10:10

Marko