views:

72

answers:

2

I have a method that creates a form in my controller:

...
sbReturn.Append(String.Format("<p id='planSetupAddNewEffectiveDate'>"));
sbReturn.Append(String.Format("<label for='txtPlanSetupAddNewEffectiveDate'>Effective Date </label>"));
sbReturn.Append(String.Format("<input type='text' id='txtPlanSetupAddNewEffectiveDate' class='plansetupdate' />"));
sbReturn.Append(String.Format("</p>"));
...

Is there a way to attach a datepicker to that text field?

I've tried the standard

$(".plansetupdate").datepicker();

and

$("#txtPlanSetupAddNewEffectiveDate").datepicker();

but neither actually generates the datepicker. I know when trapping events from dymically added controls (ie. buttons) .live is used (ie. xxx.live('click', function()...), is there something similar for this case?

+4  A: 

You can use the .liveQuery() plugin for this, .live() didn't fully replace it, your case is a prime example, you'd do this to get the result you're after:

$(".plansetupdate").liveQuery(function() {
  $(this).datepicker();
});

For the why: The reason it isn't working currently, is because when you execute $(".plansetupdate").datepicker(); what it's doing is this:

  • Find all elements with class planetsupdate
  • Make datepickers on them

But...your element wasn't there to find when it ran, it was added later. .liveQuery() continues to look. Altneratively, if you are loading this content via $.ajax() you could rig them up in your success or complete handler, like this:

$.ajax({
  //Stuff
  success: function(data) {
     $(".plansetupdate", data).datepicker();
  }
});

This would look inside your returned data for .planetsupdate elements to add new datepickers on.

Nick Craver
Hmm...The .liveQuery was throwing an exception, but I didnt realize I could wire up the datepicker after the ajax call returns. Kind of dumb of me :) Thanks!
SlackerCoder
Brilliant suggestion using liveQuery, this has solved a massive problem I was having.
@user275074 - Welcome :) I just posted an answer to a question of yours on the same topic, hopefully the simple approach helps ;)
Nick Craver
A: 

It should work!

Are you getting this from by ajax or during normal request. Are you sure that your js code ir been executed properly (after input are created at doom).

Zote