1

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>
0

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The reason, why you need the live method is, that the element is not specified in the DOM at the beginning of the site. For all new elements during the runtime you need to use live() instead. Take a look onto the Caveats on the jQuery site, to see the differences: api.jquery.com/live
3

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("");
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.