1

I have an 'add' button that creates some dynamic textfields. The default start date and end date textfields displays the datepicker. However, the dynamically created textboxes are not displaying the datepicker. Any help would be appreciated.

$(document).ready(function() {
  $('input[name="settings[start_date][]"]').datepicker({
    maxDate: constants.MAX_YEAR + '-12-31',
    changeYear: true,
    changeMonth: true,
    dateFormat: 'yy-mm-dd'
  });

  $('input[name="settings[end_date][]"]').datepicker({
    maxDate: constants.MAX_YEAR + '-12-31',
    changeYear: true,
    changeMonth: true,
    dateFormat: 'yy-mm-dd'
  });

  $('#container').on('click', '.remove', function() {
    $(this).parent().remove();
  });

  $('#add').on('click', function() {
    var row = $('div.addNew:first').clone();
    $('#container').append(row);
  });
});
<div id="container">
  <div class="addNew" ?>
    Start Date :
    <?=form_input('settings[start_date][]', date('Y-m-d'), 'class="year-date-month-calendar input-small removetradingdates-block"')?>
    End Date :
    <?=form_input('settings[end_date][]', date('Y-m-d'), 'class="year-date-month-calendar input-small removetradingdates-block"')?>
    <input type="button" class="remove" value="Remove" />
  </div>
  <input type="button" id="add" value="Add Periods" />
</div>
Pradeep
  • 9,667
  • 13
  • 27
  • 34
Programmer
  • 157
  • 1
  • 14

2 Answers2

2

You can quite easily add a datepicker to the newly-created elements

N.B. In this example I have taken the liberty of adding a "datepicker" class to your text boxes, to make the code simpler, so make sure you alter your HTML as well. I have also reduced the amount of repetition in your code by making the datepicker options into a re-usable object:

HTML/PHP:

<div id="container">
  <div class="addNew" ?>
    Start Date :
    <?=form_input('settings[start_date][]', date('Y-m-d'), 'class="datepicker year-date-month-calendar input-small removetradingdates-block"')?>
    End Date :
    <?=form_input('settings[end_date][]', date('Y-m-d'), 'class="datepicker year-date-month-calendar input-small removetradingdates-block"')?>
    <input type="button" class="remove" value="Remove" />
  </div>
  <input type="button" id="add" value="Add Periods" />
</div>

jQuery:

//I have assumed this, just for the sake of an example:
var constants = {
  MAX_YEAR: "2020"
};

//re-usable set of options
var datePickerOptions = {
    maxDate: constants.MAX_YEAR + '-12-31',
    changeYear: true,
    changeMonth: true,
    dateFormat: 'yy-mm-dd'
  };

$(document).ready(function() {
  //set datepicker on all existing elements with "datepicker" class
  $('.datepicker').datepicker(datePickerOptions);

  $('#container').on('click', '.remove', function() {
    $(this).parent().remove();
  });

  $('#add').on('click', function() {
    var row = $('div.addNew:first').clone();
    $('#container').append(row);
    var pickers = row.find(".datepicker"); //find elements within the new row which have the "datepicker" class
    //since we cloned them, remove the "id" attributes and "hasDatepicker" class, both of which were added by jQueryUI, otherwise the datepicker will not initialise properly on these new elements   
    pickers.removeAttr("id");
    pickers.removeClass("hasDatepicker"); 
    pickers.datepicker(datePickerOptions); //add a datepicker to each new element
  });
});

You can also visit http://jsfiddle.net/yqr69eca/17/ to see a working demonstration of this code.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • when i choose any dates from the dynamic textboxes,the date of the default text field is updated. – Programmer Jun 25 '18 at 12:17
  • @Programmer I realised this was because jQueryUI also adds an "id" attribute to the element and uses this to identify it uniquely, so it knows which field to update when a date is selected. Of course it was cloning this, so when the datepicker was initialised on the cloned field, it already had an ID, and so a new one was not allocated. But since IDs must of course be unique, when it came to select a date and update the textbox, it chose the textbox using the ID and could only find the original - the copy is deemed invalid. To fix, remove the ID attribute as well - see updated answer – ADyson Jun 25 '18 at 12:49
  • Issue is fixed.Thanks – Programmer Jun 25 '18 at 13:08
  • How do i have end dates in all the dynamic controls to be greater than the start date? – Programmer Jun 28 '18 at 12:30
  • @Programmer you mean how to set that in the fields, or how to validate that the user set the values in the way you want? In either case you need to be able to compare the start date and end date, so you need to learn how to get the values of a field, convert it to a Date object and then be able to either compare it to another Date object, or create a Date object with a later time (depending on your requirement). There's my clue. If you are still stuck I suggest you ask a new question about it, as it's essentially unrelated to this question. – ADyson Jun 28 '18 at 12:34
  • i have created the jsfidddle. http://jsfiddle.net/yqr69eca/22/ Here only for the default values the end dates lesser than start dates are disabled.How do i have it for the dynamic fields as well? – Programmer Jun 28 '18 at 12:51
  • Like I said, please ask a separate question. Don't start a whole new topic in the comments of an answer. For one thing, only I will get notified of it, and secondly no-one gets any upvotes or rep points for it... Also in that fiddle, no dates appear to be disabled, and you've somehow mangled the code so that Add Periods creates two rows at a time. I suggest you fix it before you ask a question relating to it. – ADyson Jun 28 '18 at 12:56
  • separate queston is asked in https://stackoverflow.com/q/51083558/5857348 – Programmer Jun 28 '18 at 13:02
-1

write your function like this

$(document).on('click','#targetid',function(){
    /*Do something logically here*/
   // On a side note it will always work on dynamic,static elements
 });
BlackXero
  • 880
  • 4
  • 17
  • the .datepicker() function is not an event handler. It's run one-off to attach datepicker functionality to a particular element (or set of elements). So using delegated events - which I assume you're implying, although you didn't add any explanation to your answer - is irrelevant here. – ADyson Jun 25 '18 at 10:33
  • My answer is not for the datepicker, you can give your datepicker a class and an id to your button which creates the dynamic fields and by clicking,select,focus.. that particular class you will have your datepicker. I had this same situation before and this method worked for me – BlackXero Jun 25 '18 at 10:46
  • "My answer is not for the datepicker"...the question is all about the datepicker though. And you didn't explain your answer so how should we know what you mean? "by clicking,select,focus.. that particular class"...so why did you give an example using "click" instead of "focus". And if you create the datepicker every time the element is focussed, you can end up re-creating an existing one multiple times if the user goes back to that field later. Not very efficient IMHO. – ADyson Jun 25 '18 at 10:51