How to attach jQuery UI datepicker to dynamically

2020-02-12 08:11发布

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'});
    });
});

1条回答
够拽才男人
2楼-- · 2020-02-12 08:37

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"); 
    });
查看更多
登录 后发表回答