Nur Aini
Nur Aini

Reputation: 393

jquery bind datepicker and clone table row

I have a table row. which contain a few input field. There is also the select input field which is populate by a php code. which is why i am trying to use jquery clone in this problem. For the example here, i will not include the select input type because i wanted to just get datepicker to work. Below is my table.

<input type="button" id="addButton" value="Press to Add">
<table border="1" id="displayData">
  <tr id="addNew" style="display:none;">
    <td colspan='2'><input type='text' name='textTest[]'/></td>
<td><input type="text" name="date[]" class="datePickTest" readonly/></td>
  </tr>
</table>

and this is my jquery code.

$(function(){
    $("#addButton").click(function(){                  
                 $("#addNew").clone()     
                 .removeAttr('id').show().insertAfter($("#displayData tr:first"));

                 $(".datePickTest").datepicker(

                {   changeYear: true ,
            changeMonth: true ,
            dateFormat: "dd-M-yy",
          //year selection limit to date before today till 1900
        //  yearRange: "1900:" + new Date().getFullYear(),
        //  maxDate :  new Date()
        }); 

            });
     });

this code does not work. so i try

 $("#addNew").clone(true).removeAttr('id').show()
 .insertAfter($("#displayData tr:first"));

but this did clone and bind with datepicker but when i select the date, only the static row will get the value even though i click on the cloned input.

i would actually want something like this.. but using clone.

var newRow = '<tr><td colspan="3">date: <input type="text" name="date[]" class="datePickTest" readonly/></td></tr>';
$("#displayData tr:first").after($(newRow));

$(".datePickTest").datepicker(
  { changeYear: true ,
    changeMonth: true ,
    dateFormat: "dd-M-yy"
});

Upvotes: 0

Views: 2196

Answers (1)

Pradeeshnarayan
Pradeeshnarayan

Reputation: 1235

You have to assing the classname datePickTest while clone the element. Because while calling datepicker function, it will change the hidden rows classname itself.

html

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<input type="button" id="addButton" value="Press to Add">
<table border="1" id="displayData">
  <tr id="addNew" style="display:none;">
    <td>Date: <input type="text" name="date[]" readonly/></td>
  </tr>
</table>

jquery

$(function(){
    $("#addButton").click(function(){
        tr = $("#addNew").clone().removeAttr('id').show()
        tr.find('input[type="text"]').addClass("datePickTest");
        tr.insertAfter($("#displayData tr:first"));
         $(".datePickTest").datepicker(
             {   changeYear: true ,
                changeMonth: true ,
                dateFormat: "dd-M-yy",
        });

    });
});

Please check the FIDDLE

Upvotes: 1

Related Questions