I have added fields to my form dynamically using a for-loop, which works fine. However, the fields i'm adding are supposed to be DatePickers and they require javascript as well. I've tried giving them a unique ID from the integer that the loops iterates through, but it does not seem to find them?
This is the view:
@model ProjectName.Models.ViewModels.GuestCreatorViewModel
@using Res = ProjectName.Resources.Resources
@for (int i = 1; i <= Model.NumOfGuests; i++)
{
<div class="row">
<div class="form-group">
@Html.Label(Res.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.Label(Res.Period, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.DateRange, new { id = "dateRangePicker" + i, htmlAttributes = new { @class = "form-control" }, @readonly = true })
@Html.ValidationMessageFor(model => model.DateRange, "", new { @class = "text-danger" })
</div>
</div>
</div>
<script type="text/javascript">
$('input[name="dateRangePicker'+@i'"]').daterangepicker();
$('#dateRangePicker'+ @i'').daterangepicker({
"showWeekNumbers": true
}, function (start, end, label) {
console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
});
</script>
}
If I remove the "+ @i" in the javascript and "+ i" in the html.helper it works for the first row, but all rows/fields after does not work (I guess because the script is outside their scope). If I keep them, none of the fields work with the script.
Am I doing something wrong when dynamically naming them or something?
The DateRangePicker is taken from here, but I've also tried other datepickers where the same issue occurs.