views:

21

answers:

3

Given:

<input id="datepicker" type="text" />

Where the id = datepicker tells the javascript to attach all the datepicker code to the form element, how do I turn this into a server control?

For example:

<input runat="server" id="datepicker" type="text" />

Doesn't work because ASP.net generates it's own ID's.

Edit

<asp:TextBox runat="server" ID="dateTo" class="datepicker"></asp:TextBox>

Renders as

<input name="ctl00$mainContent$dateTo" type="text" id="ctl00_mainContent_dateTo" class="datepicker" />

And doesn't work!

+2  A: 

It's not a good idea to bind a datepicker to an ID. better is to give it to the class (in asp.net: CssClass) then, multiple inputs can have datepickers. so in short, bind the datepicker to a class. This also fixes your asp.net problem about the ID's

<input id="aspid" class="datepicker" type="text" />

<asp:TextBox runat="server" ID="dateTo" CssClass="datepicker"></asp:TextBox>

then in your jquery selector:

 $(".datepicker").datepicker()
Stefanvds
Setting class="datepicker" doesn't seem to work with jquery-ui
Tom Gullen
A: 

You need to reference the client ID of the control in the Jquery datepicker initialisation, like such:

$(function() {
    $("#<%=dateTo.ClientID %>").datepicker();
});

Seems to work :)

Tom Gullen
but it aint very extendable now is it... if you place the jquery binding code in your masterpage, then, to make a datepicker, the only thing you need to do is add the CssClass to your input and you're done.
Stefanvds
+2  A: 

I think it's a good practice to have a class which triggers a date picker to be created for everything that has it, such as 'js-date-picker'

then to avoid duplication of code, you can just write the following JS once:

$(document).ready(function() { 
    $(".js-date-picker").datepicker();
});

to get ASP.net to set a class on the textbox correctly so it uses this class, just add CssClass="js-date-picker" to the tag:

<asp:TextBox runat="server" ID="dateTo" CssClass="js-date-picker" />

Hope this clarifies things for you.

clocKwize