2

I've downloaded a calendar script, that when the input element is click a calendar will popup.

<script language="JavaScript">
  $(function() {
        $( ".datepicker" ).datepicker();                
  });   
</script>

<input class='datepicker' />

The above code works fine.

But when the element is coming from a javascript...

<script language="JavaScript">
function showElement()
{
    $('#mydiv').html("<input class='datepicker' />");

}
</script>

<div id='mydiv'></div>

The calendar don't shows up as the input is clicked. I think there is no error in the downloaded script. I think I need to do something to make this calendar appears even if the element is created by a javascript. What should I modify? Thanks!

2
  • 1
    I think this has nothing to do with creating the element from JavaScript. I think the problem is that you are creating the element after $( ".datepicker" ).datepicker(); has already been called. Maybe you could try calling it again right after creating the input element? Commented Jun 15, 2013 at 6:58
  • @JLRishe great. It's works fine now. I now called $( ".datepicker" ).datepicker(); after creating the elemet. Thank you so much Commented Jun 15, 2013 at 7:03

1 Answer 1

1

Change your function to:

function showElement()
{
    $('#mydiv').html("<input class='datepicker' />");
    $( ".datepicker" ).datepicker();

}

Or even better, do the following:

function showDatePicker(selector) {
    $(selector).datepicker();
}

function showElement()
{
    $('#mydiv').html("<input class='datepicker' />");
    showDatePicker(".datepicker");
}

This way you can show the date picker whenever you want by calling the showDatePicker() function for any element that matches the selector you pass as a parameter to the function. Of course in your case you would only want to call it after you have called the showElement() function

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

2 Comments

Why to do global ".datepicker" match again? It will be enough to match the added element only to call datepicker() on it.
Good point DrakeES, I just used the jQuery selector that was originally used to be consistent, however you can see in my preferred answer I have provided for using any selector by passing it as a parameter.

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.