Search code examples
javascriptasp.netpostbackdatetimepickertimepicker

accessing TimePicker value in Javascript


i have i Timepicker in my page and i have the well-known issue of it not being updated with the new selected time during the postbacks and keeps the initial set time even though it's been correctly set in the first time . so i know that i should have some javascript storing selected times in hiddenfield to be accessed later in my code behind. now the problem is i don't know how to access the value of the timePicker in javascript. i'm using ASP.NET TimePicker

Here is my html declaration of the timepicker :

<cc1:TimeSelector ID="TimeSelectorDebut" BrhaviorID="TimeSelectorDebut" runat="server" DisplaySeconds="false" SelectedTimeFormat="TwentyFour"  OnChange ="SaveNewTimes()"></cc1:TimeSelector>

Solution

  • This should work:

    function getTime(timePicker) {
        var timeSel = document.getElementById(timePicker);
        var inputs = timeSel.getElementsByTagName("input");
        if (inputs.length === 6) {
            var hour = inputs[0].value;
            var minutes = inputs[2].value;
            var seconds = inputs[4].value;
            var meridiem = inputs[5].value;
            return hour + ":" + minutes + ":" + seconds + " " + meridiem;
        }
    }
    

    Usage:

    var time = getTime('<%=TimeSelector1.ClientID %>');
    console.log(time);
    

    Note: Make sure this is included after the elements are loaded (window.load, document.ready or at the bottom of your page, after body tag).

    Result: 02:14:00 PM 
    

    This, of course is a string, but you can easily turn that into a Date object:

    return new Date(null, null, null, hour, minutes, seconds);