Using JQuery datepicker() with CSS class in ASP.net for dynamically generated TemplateFields

I have implemented TemplateFields in a Gridview to dynamically create textboxes as records are added. However, due to the limitation of not being able to have ASP controls with the same ID's, using ClientIDMode=Static is not an option for these controls.

<div class="row">
    <div class="col-md-12">
     <div class="form-horizontal">
      <div class="control-group">
        <asp:Panel ID="pnlDevMembers" runat="server" Height="100%" ScrollBars="None" Visible="true" Width="100%">
          <asp:GridView ID="grdDevSignoffs" runat="server" OnRowCommand="grdDevSignoffs_RowCommand" AutoGenerateColumns="false" CssClass="table-striped" cellspacing="30" GridLines="None" CellPadding="10" RowStyle-Height="40px" HorizontalAlign="Center" BorderStyle="None">

            <Columns>
            <asp:BoundField HeaderText="Event" DataField="desc" ControlStyle-Width="100px"  />
            <asp:TemplateField ControlStyle-BorderStyle="None"  ControlStyle-BorderColor="Transparent" ItemStyle-HorizontalAlign="Center" HeaderText="&nbsp;&nbsp;&nbsp;Name">
             <ItemTemplate>
           <div style="padding-left: 10px; padding-right: 10px;"><%#Eval("Lastname")%>, <%#Eval("FirstName")%></div>
           </ItemTemplate>
             </asp:TemplateField>
             <asp:TemplateField HeaderStyle-HorizontalAlign="Center" HeaderText="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Signoff Date" HeaderStyle-BorderStyle="None" HeaderStyle-BorderWidth="0px" ControlStyle-Width="100px" 
                                            ItemStyle-HorizontalAlign="Center">
                                            <ItemTemplate>
                                               <asp:textbox ID="txtDevDate" runat="server" Text='<%# Bind("SignOffDate") %>' CssClass="form-control input-sm datepick" Width="140" style="margin-left: 20px;margin-right: 20px;"/>
                                            </ItemTemplate>
                                        </asp:TemplateField>
             <asp:TemplateField ControlStyle-BorderStyle="None"  ControlStyle-BorderColor="Transparent" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                          <asp:LinkButton ID="btnSignoffDevUser" runat="server" CssClass="btn btn-small btn-success" CommandName="signoffRecord" CommandArgument="<% CType(Container,GridViewRow).RowIndex %>"><i class="glyphicon glyphicon-ok"></i> Signoff</asp:LinkButton>&nbsp;&nbsp;&nbsp;&nbsp                            
                 </ItemTemplate>                    
               </asp:TemplateField>

                  <asp:TemplateField ControlStyle-BorderStyle="None"  ControlStyle-BorderColor="Transparent" ItemStyle-HorizontalAlign="Center">
                  <ItemTemplate>
                 <asp:LinkButton ID="btnUndoSignoffDevUser" runat="server" CssClass="btn btn-small btn-danger" CommandName="UndoRecordSignoff" CommandArgument="<% CType(Container,GridViewRow).RowIndex %>"><i class="glyphicon glyphicon-remove"></i> Undo Signoff</asp:LinkButton>&nbsp;&nbsp;&nbsp;&nbsp
                 </ItemTemplate>
                </asp:TemplateField>
               <asp:TemplateField ControlStyle-BorderStyle="None"  ControlStyle-BorderColor="Transparent" ItemStyle-HorizontalAlign="Center" >
                    <ItemTemplate>
                          <asp:LinkButton ID="btnRemoveDevUser" runat="server" CssClass="btn btn-small btn-danger" CommandName="removeRecord" CommandArgument="<% CType(Container,GridViewRow).RowIndex %>"><i class="glyphicon glyphicon-minus"></i></asp:LinkButton>
                 </ItemTemplate>
               </asp:TemplateField>
            </Columns>
          </asp:GridView>
        </asp:Panel>
        </div>
      </div>
    </div><!--end rw1col1-->
 </div>

In an attempt to trigger the datepicker function when elements with the CSS class "form-control input-sm datepick" are clicked, I assigned this class to the controls. However, the JavaScript code doesn't seem to be executing properly. The same script works perfectly fine when tested against a control with a static ID, which leads me to believe it's not an issue with the JS structure.

<script type="text/javascript">
    $(document).ready(function () {
        $('.form-control input-sm datepick').each(function () {
            $(this).datepicker();
        });
    }); 
</script>

Is there a way to implement the datepicker for dynamically created fields considering that the IDs are generated at runtime?

Answer №1

Give it a shot

$('body').on('focus', function(){
    $('.datepick').datepicker();
});​

Answer №2

Here is the solution that worked:

   $(document).ready(function () {
        $('.datepick').each(function () {
            $(this).datepicker();
        });
    }); 

Special thanks to javc91 for your assistance. The $(.datepick) snippet helped me realize that I only needed to target items with that specific class, rather than the entire "form-control input-sm datepick" class. This adjustment was key in making the JavaScript function properly. Much appreciated!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to store temporary request data in EWL?

I am looking to maintain state that is only valid for the duration of a single request. In the past, I was able to manually store state in AppRequestState, but it seems like that capability no longer exists. My backup plan is to store the state in Session ...

Modify the displayed text according to the content of the input field in HTML

I need to update the value of an <h3> tag based on user input in an input field. Here is my current code snippet: <input id="Medication" name="Medication" size="50" type="text" value=""> <script> $(document).ready(function () { $(&apos ...

Executing functions on Angular scope within Underscore Template

Having an underscore template being invoked from an Angular controller, there is a dropdown in the template and an onchange function called on the dropdown. Despite several attempts to get the method triggered in the onchange event, using this code <se ...

What is the best method for passing information to my frontend JavaScript files using Express?

When using ejs to render my html pages, I pass in data in the following manner: collection.find({}).toArray( function (err, results) { res.render('index', { results: results, ...

How to efficiently switch between classes in Ember Octane using Handlebars?

What is the best way to toggle between displaying a class on and off using Ember.js Octane? Should I use an @action or @tracked in this case? <img src="flower.jpg" alt="flower" class="display-on"> or <img src="flower.jpg" alt="flower" class=" ...

A guide on how to alternate between ng-hide and ng-show using separate controllers by utilizing a shared factory toggle state instance

Using Angular 1.x, I have implemented two controllers where I want to display controller_2 if controller_1 is hidden. To achieve this, I am utilizing a factory method. Here is the snippet of my HTML code:- <div ng-controller="controller_1 as c1" ng- ...

Methods for delivering static resources on multiple routes in Express JS

Is there a way to effectively serve static resources for all routes in Express JS? I attempted to serve files with static resources using the following code snippet: app.use(Express.static(`${this.PATH}`)); app.use(Cors()); app.use(Express.json()); app.g ...

Steps to retrieve a rejected object with an error stored in it in the following .then() function

Within my chain of promises, there is a specific promise that needs to log an error but pass the remaining data to the next .then() const parseQuery = (movies) => { return new Promise((resolve, reject) => { const queries = Object.keys( ...

What causes the Next 13 App to reload when the route is changed?

I am currently working on the Next 13 Application and facing an issue where clicking on navigation links from the sidebar changes the route, but unfortunately, the application is getting reloaded. It should ideally replace the component directly without re ...

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...

Restricting the Vue for-loop results to display only the current item in use

Currently, I am utilizing a for-loop to retrieve all of my posts, followed by employing a partial to obtain a list of all the usersThatUpvoted on that post. <div v-for="p in posts" style="padding: 16px"> <div> &l ...

The intl-tel-input dropdown feature is malfunctioning on mobile browsers

Currently, I have integrated the intl-tel-input library into my project for selecting international telephone numbers from a dropdown menu. https://i.sstatic.net/vPfpd.png While accessing the application on a web browser, the country flags display correc ...

Is there a way to show a fallback message for unsupported video file formats?

When incorporating a video element on my webpage, I typically use the following code: <video src="some source" controls> Error message </video> Based on my knowledge, the "Error message" will only appear if the browser does not support the ...

Guide on creating a line chart resembling the one in Highcharts library

I would like to create a line chart using the HighChart library, using data similar to what is shown in the image below. However, I am not familiar with HTML, CSS, or JavaScript and don't know how to go about developing this. Can anyone provide guidan ...

Creating a visual representation from tabular data: A step-by-step guide

Hello there! I appreciate any assistance you can provide! Could you guide me on creating a script (using PHP or JavaScript) that functions as a chart constructor? The input values should be data retrieved from a database table and displayed on the web pa ...

Tips for customizing the appearance of Angular Material select drop down overlay

In my project, there is an angular component named currency-selector with its dedicated css file defining the styling as shown below: .currency-select { position: absolute; top: 5px; right: 80px; z-index: 1000000; color: #DD642A; f ...

Tips for utilizing a switch statement

I'm a beginner in JavaScript and recently learned about the switch statement. I have an exercise where I need to convert numbers 1-10 into words like "one", "two", "three"... This is what I have tried so far: function sayNum(){ let numberArray = [ ...

"Explore the dropdown options on the Twitter Bootstrap menu by hovering your cursor

Is there a way to modify the code so that when hovering over a dropdown menu created with Twitter Bootstrap 3, the menu expands and users are able to click on the expanded links? The HTML code I came up with is as follows: <nav> ...

Ways to pass properties while using render in reachrouterdomv6?

Currently, I am enrolled in a Udemy course, but the information provided is based on v5. I am struggling to understand the equivalent of "render" and how to pass props with it. Additionally, there seems to be an issue with the code - if the element is un ...

An issue arises with the Datatables destroy function

Utilizing datatables.js to generate a report table on my page with filters. However, when applying any of the filters, the data returned has varying column counts which prompts me to destroy and recreate the table. Unfortunately, an error message pops up ...