I have several textbox elements being generated in a foreach, like this:
@foreach(var thing in Model.Things)
{
<tr>
<td>@Html.TextBoxFor(m => thing.StartDate, new { id = "thingStartDate", @class = "thingDatePicker" })</td>
</tr>
}
I’m attaching jQuery datepickers to each textbox, like this:
$(document).ready(function(){
$(".thingDatePicker").datepicker({ dateFormat: "mm/dd/yy" });
});
The datepickers all fire correctly on each textbox, in the correct positions. But when I select a date from any of them, it only populates the first textbox. How do I make sure each datepicker is firmly associated with its textbox?
You seem to be using the same id for all your textboxes (
id="thingStartDate") which obviously results in invalid HTML. So either remove the id attribute or make sure you don’t get dupes. I would probably remove it as you are using a class selector and this id serves no purpose at all:Also I hope you realize that
m => thing.StartDatewill generate incorrect names for those textboxes. It will usename="StartDate"instead ofname="Things[xxx].StartDate"which might get you into troubles later when you attempt to bind back to your view model. For this purpose I recommend scraping theforeachloops in view in favor of editor/display templates:and inside the corresponding editor template (
~/Views/Shared/EditorTemplates/Thing.cshtml)