Question

The runat="server" is breaking my jquery. I have two input, but for testing purpose added runat="server" in only one of those. Actually , I need to add on both.

Below you can find JS script to trigger the datetimepicker: note: dateTo has runat="server" set and tried to change the way JS trying to get its ID, but still not working.

<script>
        $(function(){
            $("#dateFrom").datetimepicker();
            $("#<%=dateTo%>").datetimepicker();
        });
</script>

Here you can find the HTML input using runat="server" or not into asp.net code.

    <tr>
        <td>
             <input type="text" id="dateFrom" name="dateFrom" value="" class="dateFrom" />
        </td>
        <td >
             <input type="text" id="dateTo" name="dateTo" runat="server" value="" class="dateTo" /> 
        </td>
    </tr>

Does anybody has any idea,hint.....? thank you

Was it helpful?

Solution

Use ClientID to get the generated Id of a server side control:

$("#<%=dateTo.ClientID%>").datetimepicker();

ASP.NET will generate a specific id attribute that is different from the id attribute of the server side control, so you need to use the generated value in order to access it from jQuery.

OTHER TIPS

Since you're supplying class names, I suggest simply using those.

$(function(){
    $(".dateTo, .dateFrom").datetimepicker();
});

Alternatively, you could give any "date" field on your form a class of "date" and use that:

$(function(){
    $(".date").datetimepicker();
});

This is a common pattern for client-side validation, and also allows you to provide context clues through styling with CSS.

If you're using .NET 4 you can set the ClientIDMode attribute to Static. This will prevent the framework from changing the element's ID:

<input type="text" id="dateTo" name="dateTo" runat="server" 
       ClientIDMode="Static" class="dateTo" value=""  /> 

ASP.NET will treat the inputs as server-side controls when runat=server is added, and this will result in transformed identifiers of those inputs so that they start with a container prefix (something like ctl00_), hence 'breaking' your jQuery selectors.

If you're using .NET 4 then you can disable these transformations by altering the ClientIDMode. Otherwise you will need to include the prefix in your selectors, or refactor your selectors to be independent of ID and somewhat distinct for selection by other means.

Use this to get correct client id for server controls

$('[id$=dateTo]').datetimepicker();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top