Home > Net >  How do I attach datepickers to text boxes with the same ID?
How do I attach datepickers to text boxes with the same ID?

Time:10-21

I have an ASPX that has a repeater. Inside the repeater is a text box with a JQuery datepicker attached to it. The text box's ID is static, so it is the same for all of those items within the repeater. However, when I make a change to the second or subsequent repeater item's date box using a datepicker, it changes the first item's date box and leaves the one actually attached to the selected datepicker alone.

Other than the obvious solution of "don't define items with the same ID," which results in another problem that will probably end up in another question, is there a way to fix this problem?

CodePudding user response:

This example

<asp:Repeater runat="server" 
              ID="rptWhatever" 
              ClientIDMode="Predictable">
  <ItemTemplate>
    <asp:TextBox runat="server" 
                 ID="tbxWhoCares" 
                 CssClass="ImaDatePicker">
    </asp:TextBox>
  </ItemTemplate>
</asp:Repeater>

Will render the textbox to something like:

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

So regardless of the id you should be able to do this in your script:

$(".ImaDatePicker").datepicker();

The problem with non-unique ID's is a big one but should be an easy fix if you set the attributes in the Repeater to ClientIDMode="Predictable" and leave the same attribute in the TextBox to its default.

Update

It seems jquery UI datepicker requires a unique id. So you can select multiple inputs using a common css class but the id's must be unique otherwise you run into that problem.

It shouldn't work that way...but it does.

Alternatively you could just use the native <input type="date" ... />

$(function() {
  $(".ImaDatePicker").datepicker();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/theme.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css" rel="stylesheet"/><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>

<input id="tbxWhoCares" type="text"  />
<input id="tbxWhoCares" type="text"  />
<input id="tbxWhoCares" type="text"  />
<br><br><br>
<input id="tbxWhoCares_1" type="text"  />
<input id="tbxWhoCares_2" type="text"  />
<input id="tbxWhoCares_3" type="text"  />

  • Related