Home » javascript » jQuery Datapicker cannot attach itself to an HTML element using the id selector in a APS.net

jQuery Datapicker cannot attach itself to an HTML element using the id selector in a APS.net

When using the jQuery Datapicker in connection with a HTML form, I have had cases where the Datepicker has been unable to attatch itself to a HTML element by its id selector name. Browsing the internet for a possible solution to this problem, I found an explanation stating that the problem is that the javascript attaching the Datapicker to the HTML element executes before the browser has completed rendering the HTML and DOM structure. The solution would be to postpone the execution of the javascript until the HTML structure has been completely rendered. Whether this is a valid explanation or not, I cannot say, however I can describe what has worked for me in a similar situation.

In connection with a ASP.NET form, where the Datepicker was attached to a TextBox having the attribute  id=”txtDatePicker”, the Datapicker wasn’t appearing as expected when users clicked in the text field.

The code which wasn’t working properly was as follows:

$(document).ready(function() {
$(function() {
$("#txtPickupDate" ).datepicker({ dateFormat: "D, d M yy" }); });

With just a few changes the Datepicker starts working properly. Here is the code that actually works for me:

var txtDatePicker = '#txtDatePicker';
$(document).ready(function() {
$(function() {
$( txtPickupDate ).datepicker({ dateFormat: "D, d M yy" }); });

The first change is the addition of the first line of code , in which a variable containing the id selector’s name: “txtDatePicker” is declared. The second change is in the fourth line where the variable is then used to reference the id selector instead of using the literal value to access the input field.  These changes were enough to get the Datepicker working for me!

By Jens Vejrup Lassen

Post a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>