user1414157
user1414157

Reputation: 53

pass the value of datetimepicker to codebehind (c#)

i want to pass the value of a datetimepicker to my Codebehind(C#) and save it to a variable in C#.

I tried it with a hiddenfield but it don't works.

here is the js code:

var dates = $("#ArrivalStartDatepicker").datetimepicker({
                            defaultDate: "+lw",
                            dateFormat: 'dd-mm-yy',
                            changeMonth: true,
                            numberOfMonths: 2,
                            ampm: true,
                            stepMinute: 10,
                            minuteGrid: 10,
                            onSelect: function (selectedDate) {
                                    document.getElementById("ArrivalStart").value = dates.datetimepicker('getDate');
                                }
                            });

the hiddenfield:

<div>
          <input type="hidden" id="ArrivalStart" runat="server"/> 
</div>

when I choose a date or a time firebug throws the following error:

document.getElementById("ArrivalStart") is null

this tells me that the ArrivalStart-Field isn't accesible in JS.

how can i manage this?

greetz

Tobi

Upvotes: 3

Views: 2201

Answers (2)

Hans Kesting
Hans Kesting

Reputation: 39284

Instead of

 document.getElementById("ArrivalStart")

use

  document.getElementById("<%= ArrivalStart.ClientId %>")

That way you inject the ID that ASP.Net created.

EDIT
This javascript fragment needs to be in the aspx file (not a separate js file), as ASP.Net needs to process that <%= .. %> block and needs access to the ArrivalStart member.

Upvotes: 4

Charleh
Charleh

Reputation: 14002

When you make a control runat=server, c# takes responsibility of rendering the element. Therefore most of the time it will re-write the ID of the control as it needs to take into account what form the control is in and also if it's nested within a data repeater or some other repeating control.

If you run the page and click 'view source' does the ID of the element still equal 'ArrivalStart' or has the ID been rewritten?

If it doesn't you can use C# to write the ClientID of the control (Control.ClientID) into your jQuery script

I could be barking up the wrong tree though :)

Upvotes: 1

Related Questions