简体   繁体   English

动态添加有javascript的字段,形成

[英]Dynamically add fields that have javascript, to form

I have added fields to my form dynamically using a for-loop, which works fine.我已经使用 for 循环向我的表单动态添加了字段,效果很好。 However, the fields i'm adding are supposed to be DatePickers and they require javascript as well.但是,我添加的字段应该是 DatePickers,它们也需要 javascript。 I've tried giving them a unique ID from the integer that the loops iterates through, but it does not seem to find them?我试过给他们一个来自循环迭代的 integer 的唯一 ID,但它似乎没有找到它们?

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).如果我删除 javascript 中的“+ @i”和 html.helper 中的“+ i”,它适用于第一行,但之后的所有行/字段都不起作用(我猜是因为脚本超出了它们的范围)。 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. DateRangePicker 取自此处,但我也尝试了其他出现相同问题的日期选择器。

I would not use the ID to assign the datepicker but a css class (even a not defined one, just for this purpose).我不会使用 ID 来分配日期选择器,而是使用 css class (即使是未定义的,仅用于此目的)。 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:并且 JS 代码应该在 for 语句之外,可能在 document.ready function 中,如下所示:

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

Hope this helps希望这可以帮助

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:它将呈现这个无用的属性: htmlAttributes它应该是:

@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.第二:您应该做的是在 for 循环中生成所有 HTML,然后使用单个脚本标记立即初始化 daterangepicker 控件。 You can get all inputs with a class instead of using their ids.您可以使用 class 而不是使用它们的 ID 来获取所有输入。

@{
        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创建日期选择器后,我向每个选择器添加一个自定义 css class: custom-date-picker 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在 for 循环呈现 HTML 之后,我创建了一个脚本标签并使用选择器.custom-date-picker获取所有输入,并从中创建 daterangepicker 控件

PS I used a simplified version of your code for the sake of explanation. PS为了解释起见,我使用了您的代码的简化版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM