Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery datepicker on dynamically generated rows

I am dynamically generating table rows using the following javascript codes:

$('#addNew').on('click', function() {
    var clone = $('table.table-responsive tr.cloneme:first').clone();
    console.log(clone);
    clone.append("<td><button class='deleteAdded btn btn-danger'>Remove</button></td>")
    $('table.table-responsive').append(clone);
    calculateSum();
});

And this is my script for appending jQuery calendar to date inputs

$(function() {
    $('input').filter('.datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
    });
});

Now the problem I am facing is that the jQuery calendar pops up only in the first row. It doesn't work on the rows that are generated.

This in my html

<td>
    <input type="text" class="form-control datepicker" name="invoiceDate[]" readonly="readonly" />
</td>

Please tell me how to make jQuery calendar work on all the rows that are dynamically generated. Looked around Google but nothing helped.

Thanks in advance.

like image 864
Indra Gotamey Avatar asked Mar 01 '26 21:03

Indra Gotamey


1 Answers

You have to initiate the datepicker after the new rows are created

jQuery(function($) {
  //create a original copy of the row to clone later
  var $tr = $('table.table-responsive tr.cloneme:first').clone();

  //add dp to existing rows
  addDP($('input.datepicker'));

  $('#addNew').on('click', function() {
    var clone = $tr.clone();
    console.log(clone);
    clone.append("<td><button class='deleteAdded btn btn-danger'>Remove</button></td>");
    //add dp to the new row
    addDP(clone.find('input.datepicker'));
    $('table.table-responsive').append(clone);
    calculateSum();
  });

  function addDP($els) {
    $els.datepicker({
      dateFormat: 'yy-mm-dd',
      changeMonth: true,
      changeYear: true,
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<table class="table-responsive">
  <tr class="cloneme">
    <td>
      <input type="text" class="form-control datepicker" name="invoiceDate[]" readonly="readonly" />
    </td>
  </tr>
</table>
<button id="addNew">Add</button>
like image 105
Arun P Johny Avatar answered Mar 03 '26 09:03

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!