Tom
Tom

Reputation: 12988

jquery - dynamically created button not working

I have a piece of code which inserts a link into a p tag when a date is selected from the datepicker.

For some reason the .click function of this dynamically created link does not work - but it does work if I hard code the button in exactly the same place rather than inserting it dynamically.

Any ideas why this is happening??

    $(document).ready(function(){

    $( "#MR1 > #datepicker" ).datepicker({
        beforeShowDay: function(date){ return [(date.getDay() == 1 || date.getDay() == 4), ""] },
        showOn: "button",
        buttonText: "Book now...",
        showWeek: true,
        firstDay: 1,
        onSelect: function(date) { $("#MR1 > #selecteddate").prepend("Date: " + $("#MR1 > #datepicker").val() + " - <a href='javascript:;' class='cleardate'>clear date</a>"); },
        dateFormat: "DD, d MM, yy",
        altField: "#datepickeralt",
        altFormat: "dd/mm/yy",
        navigationAsDateFormat: true,
        minDate: 0,
    });

    $("#MR1 > #selecteddate > .cleardate").click(function(){
        $("#MR1 > #selecteddate").html("");
        $("#MR1 > #datepicker").datepicker("setDate", null);
        $("#MR1 > #datepickeralt").val("");
    });

});

body code as follows...

<div id="MR1">
<p id="selecteddate"></p>
<input type="text" id="datepicker" style="display:none;">
<input type="text" id="datepickeralt" disabled="disabled" style="display:none;">
</div>

Upvotes: 1

Views: 1950

Answers (2)

Ben Everard
Ben Everard

Reputation: 13804

You need to use the .live() method instead.

$("#MR1 > #selecteddate > .cleardate").live('click',function(){
    $("#MR1 > #selecteddate").html("");
    $("#MR1 > #datepicker").datepicker("setDate", null);
    $("#MR1 > #datepickeralt").val("");
});

jQuery events work from the DOM generated at the page load, and thus any dynamically generated content after is ignored. .live() uses the body element as context and finds any matches for the selector you specified, thus maintaining the "bind" after the content has been added.

I had a similar problem, it's a fairly common question.

Upvotes: 8

Jamiec
Jamiec

Reputation: 136074

you need to use .live instead of .click when dynamically adding elements.

$("#MR1 > #selecteddate > .cleardate").live('click',function(){
        $("#MR1 > #selecteddate").html("");
        $("#MR1 > #datepicker").datepicker("setDate", null);
        $("#MR1 > #datepickeralt").val("");
    });

Upvotes: 3

Related Questions