Computer Programming web Web programming Tips



Datepicker With Cloned Fields

By Sergey Skudaev

This is a code to add datepicker to a single field. If id="mydate", then using id the code is:

$(function() {
$(#mydate).datepicker();
});

If class="mydate", then using class the code is:

$(function() {
$(.mydate).datepicker();
});

But when you create an array of cloned fields with clone() method, this code above is not working!





I modified the original code to add a jquery datepicker to each cloned date field. Now, if a user clickes inside the date field the calendar is displayed.

<script type="text/javascript">
  $(document).ready(function(){

   var i=0;

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

	$('<tr class="cloned1"> <td style="text-align:left; width:100px;"> DOB:       <input type="text" name="clonedA[]" size="30" onmousedown="$(this).datepicker();" onfocus="toDefault(this);"/> </td> </tr>').fadeIn("slow").appendTo("#poll1");

			i++;
    });

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

	if(i > 0)
	{
  $('.cloned1:last').remove();

			i--;
	}

	    if(i < 0)
			i=0;

   });

  });
</script>

Click the Plus icon as many times as you wish and record will be cloned.

  

It is important to use onmousedown event to invoke datepicker. If I used onclick event then the calendar is displayed only on the second click.

You can clone several fields at once. Here, one of the fields is a free text and another is date. This is the code.

<script type="text/javascript">
  $(document).ready(function(){

   var i=0;

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

	$('<tr class="cloned2"> <td style="text-align:left;"> <label>Name:</label> <input type="text" name="name[]" /></td> <td style="text-align:left;"> <label>DOB:</label> <input type="text" name="cloned[]" size="30" onmousedown="$(this).datepicker();" /> </td></tr>'). fadeIn("slow"). appendTo("#poll2");

			i++;
    });

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

	if(i > 0)
	{
  $('.cloned2:last').remove();

			i--;
	}

	    if(i < 0)
			i=0;

   });

  });
</script>

It is important to use image instead of button. When I try to use button for plus to clone a record, the page was submitted when I click it. That is why I changed the button to the image of the button.

   




 

My eBooks on Amazon.com

Subscribe to our mail list to receive free code examples.

Comments

No comments yet.

Add Comment

* Required information
(never displayed)
 
Smile Sad Huh Laugh Mad Tongue Crying Grin Wink Scared Cool Sleep Blush Unsure Shocked
 
1000
What is the day after Friday?
 
Enter answer:
Captcha
Refresh
 
Enter code:
 
Notify me of new comments via email.
 
Remember my form inputs on this computer.
 
I have read and understand the privacy policy. *
 
I have read and agree to the terms and conditions. *
 
 
Powered by Commentics