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?

Garis M Suero
  • 7,974
  • 7
  • 45
  • 68
Francisco Ochoa
  • 1,538
  • 4
  • 19
  • 43

3 Answers3

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.

Community
  • 1
  • 1
Gazillion
  • 4,822
  • 11
  • 42
  • 59
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)

Garis M Suero
  • 7,974
  • 7
  • 45
  • 68
0
$('#addScnt1').live('click', function() {
    var newElement = $('all your html'); //then append it wherever

    newElement.find('.input-selector').datepicker();
});
Robin Maben
  • 22,194
  • 16
  • 64
  • 99