2

I'm adding a date picker to dynamically generated fields.

('#addScnt1').live('click', function() {
$('<p class="textocampodetexto" style="margin-left:20px; margin-top:20px;"> 
<label for="p_scnts1">  <input id="au_fechainicioperiodo2" 
name="au_fechainicioperiodo2" type="text" size="7"  
value="" /> </p>').appendTo(scntDiv);

Those fields are added when I click an 'Add Field' button.

The date picker doesn't appear when I click on the generated field. I know the datepicker is working because I put the code outside the javascript code and it works.

How can I achieve this then?

2
  • Where do you call .datepicker()? Commented Apr 17, 2012 at 19:18
  • 1
    Please see this answer in order to help yourself with it. stackoverflow.com/questions/1396536/… Commented Apr 17, 2012 at 19:19

3 Answers 3

2

You're going to have to reattach the datepicker to your input field.

Try the solution found here: Why does jQuery UI's datepicker break with a dynamic DOM?

The code isn't identical to yours but if you could extract the input field from your selector you could do it.

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

Comments

1

Your code should work like this ( LIVE DEMO ):

$(function () 
{
  $('#addScnt1').click(function() {

    $('<p class="textocampodetexto" style="margin-left:20px; margin-top:20px;"><label for="p_scnts1">  <input id="au_fechainicioperiodo2" name="au_fechainicioperiodo2" type="text" size="7" value="" /> </p>').appendTo(scntDiv);
    $('#au_fechainicioperiodo2').datepicker(
    {
        showOn: "both",
        dateFormat: "dd M yy",
        firstDay: 1, 
        changeFirstDay: false
    });
  });
});

(NOTE: I'm supposing that the variable scntDiv is defined with an DOM object before this call)

Comments

0
$('#addScnt1').live('click', function() {
    var newElement = $('all your html'); //then append it wherever

    newElement.find('.input-selector').datepicker();
});

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.