0

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.

2 Answers 2

1

First: This syntax is incorrect:

@Html.TextBoxFor(model => model.DateRange, new { id = "dateRangePicker" + i, htmlAttributes = new { @class = "form-control" }, @readonly = true })

It will render this useless attribute: htmlAttributes It should be:

@Html.TextBoxFor(model => model.DateRange, new { id = "dateRangePicker" + i, @class= "form-control", @readonly = true })

I guess it is a typo.

Second: What you should do is generate all your HTML in the for loop, and use a single script tag after that to initialize the daterangepicker controls at once. You can get all inputs with a class instead of using their ids.

@{
        int numOfGuests = 2;
    }
    @for (int i = 1; i <= numOfGuests; i++)
    {
        <div class="row">
            <div class="form-group">

                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.DateRange, new { id = "dateRangePicker" + i, @class = "form-control custom-date-picker" , @readonly = true })
                </div>
            </div>
        </div>
    }
<script type="text/javascript">
    $('input.custom-date-picker').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>

Explanation:

  1. Upon creating the datepickers I add to each one a custom css class: custom-date-picker
  2. After the for loop renders the HTML I create a script tag and get all inputs with the selector .custom-date-picker and create daterangepicker controls out of them

P.S. I used a simplified version of your code for the sake of explanation.

Sign up to request clarification or add additional context in comments.

Comments

1

I would not use the ID to assign the datepicker but a css class (even a not defined one, just for this purpose). So you code could be something like this:

@class = "control-label col-md-2 ToBeDatePickered"

So you could try and use this simple selector:

$(".ToBeDatePickered").daterangepicker();
// ... and so on...

And the JS code should be outside the for statement, maybe in a document.ready function like this:

<script type="text/javascript">
        $(document).ready(funtion() {
             $(".ToBeDatePickered").daterangepicker();
             // ... and so on...
        });
</script>

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.