Adding a jQuery Datepicker to a dynamically added <input>
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 开发者_JS百科controls (ie. buttons) .live is used (ie. xxx.live('click', function()...), is there something similar for this case?
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.
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).
精彩评论