【问题标题】:Change JavaScript variable depending on selected DropDownList根据选定的 DropDownList 更改 JavaScript 变量
【发布时间】:2017-08-23 07:24:52
【问题描述】:

我有一张有很多 DropDownList 的表,我根据迭代更改了每个类名:

<table id="categoryTable" class="table table-striped table-hover">
    <tr class="header">
        <th>
            @Html.DisplayNameFor(model => model.Category)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.SubCategory)
        </th>
        <th>New Category</th>
        <th>New Subcategory</th>
        <th></th>
    </tr>

    @if (Model != null) { int i = 1; foreach (var item in Model) {

    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Category)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.SubCategory)
        </td>

        <td>
            <input type="hidden" class="varIteration" value="@i" /> @Html.DropDownList("CategoryId", null, "Select Your Category", htmlAttributes: new { @class = "form-control Category" + i })
        </td>
        <td>
            <input type="hidden" class=@( "SubCategoryID_CategoryID_initial"+@i) value="@i" /> @Html.DropDownList("SubCategoryId", null, "Select Your Subcategory", htmlAttributes: new { @class = "form-control SubCategory" + i })
        </td>
        <td>
            <button type="submit" class="btn">
                <i class="fa fa-check"> Update</i>
            </button>
            @*
            <input type="submit" value="Save" class="fa fa-check" />*@
        </td>
    </tr>
    i++; } }

</table>

我需要使用下面的下一个脚本根据类别中的选定值更改子类别值,该脚本仅适用于第一个类别下拉列表:

$(document).ready(function(e) {
    var iteration = $(".varIteration").val(); // iteration = 1 only
    getSubCat(true, $(".SubCategoryID_CategoryID_initial" + iteration).val(), iteration);
    $(document).on("change", ".Category" + iteration, function(event) {
        getSubCat(false, $(".Category" + iteration).val(), iteration);
    });

    function getSubCat(load, changed, iteration) {
        alert(iteration)
        var url = "/auc.accesscontrol/profiles/GetSubCatIDByCatID";
        var initialSubCat = $(".SubCategoryID_CategoryID_initial").val();
        var initialCat = $(".SubCategoryID_SubCategoryID_initial").val();
        if (load) {
            $('.Category' + iteration + ' option[value="' + initialCat + '"]').prop("selected", true);
        }
        if (initialCat == null) {
            changed = $(".Category" + iteration).val();
        }
        $.getJSON(url, {
            id: changed
        }, function(data) {
            alert(changed);
            $(".SubCategory" + iteration).empty();
            $(".SubCategory" + iteration).append("<option value= '0'>Select Your Subcategory</option>");
            $.each(data, function(index, item) {
                $(".SubCategory" + iteration).append("<option value='" + item.SubCategoryId + "'>" + item.Name + "</option>");
                $('.SubCategory' + iteration + ' option[value="' + initialSubCat + '"]').prop("selected", true);
            });
        });
    };
});

当我检查视图类名称时,会发现以下类别的下拉列表:Category1、Category2 等 和子类别:SubCategory1, Subcategory2, ....etc 隐藏的输入值:将根据最后一个 i 而改变。 需要帮助来根据所选类别下拉列表更改迭代变量。

编辑: 这是 JsonResult 函数:

public JsonResult GetSubCatIDByCatID(int id)
    {
        db.Configuration.ProxyCreationEnabled = false;
        var subCategoryList = db.SubCategory.Where(m => m.CategoryId == id).ToList();
        return Json(subCategoryList, JsonRequestBehavior.AllowGet);
    }

【问题讨论】:

  • 当您说它“不起作用”时,当您调试它时,它具体在做什么?观察到的行为与预期行为究竟哪里不匹配?
  • 只有在第一个类别下拉列表中才能正常工作,并且子类别将正确过滤...再次在第一个 &lt;tr&gt;
  • 迭代变量总是等于1
  • 点击任何其他下拉列表时没有任何反应

标签: javascript jquery html razor asp.net-mvc-5


【解决方案1】:

当你这样做时:

$(".varIteration").val()

如果有 多个 匹配元素(在这种情况下有),您希望 single 的值是多少?从行为的描述来看,它听起来像是来自 first 匹配元素的值。

获取iteration在事件中,而不是在页面级别。因此,首先将您的事件处理程序创建更改为如下内容:

$(document).on("change", "[class^=Category]", function(event) {
    //...
});

这将找到所有class“以”"Category"开头的元素,而不管类名的其余部分是什么。

然后,在该事件处理程序中,您可以动态导航 DOM 以找到您想要的 特定 iteration 值。对于您显示的 HTML,它看起来像这样:

var iteration = $(this).closest("td").find(".varIteration").val();

这基本上意味着:

从引发change 事件的元素开始,向上导航到第一个&lt;td&gt; 元素,然后在该元素中找到任何匹配的.varIteration 元素。

由于在该范围内只有 一个 .varIteration 元素,因此它将具有您正在寻找的值。

您仍然需要调整对getSubCat() 的调用,因为它也会尝试使用该值。我不清楚该功能实际上应该做什么,所以我只能提供这么多的建议。如果确实需要为iteration 的每个可能值调用它,那么您也许可以将该值范围放在某个变量中并在循环中调用getSubCat()。尽管对同一资源的 AJAX 循环调用似乎效率很低。我怀疑有更好的方法来执行您尝试使用该功能执行的任何操作。

但至少对于您在上面的 cmets 中描述的问题:

迭代变量总是等于 1

那是因为你只能得到一个值,它是第一个匹配的值。

单击任何其他下拉列表时没有任何反应

那是因为您只为那个匹配值创建了一个 change 处理程序。

所有个匹配元素创建一个单一的更改处理程序,并在该更改处理程序中动态获取您需要的值。

【讨论】:

  • 感谢@David 的帮助,但是当尝试执行 onChange 函数时,尝试使用 alert($(document).on("change", "[class^=Category]", function (event) { var iteration = $(this).closest("td").find(".varIteration").val(); })); 调试它而不更改所选类别类时,它只会触发一次
  • 如果尝试使用alert($("[class^=Category]").val());,它会得到未定义
  • @Hansy:你在这些 cmets 中尝试做的所有事情都没有意义,所以我不太确定你的意思。
  • 在下面查看我的答案,您就会明白我的意思。
  • @Hansy:所以你完全按照我在回答中的建议解决了这个问题。很高兴知道。
【解决方案2】:

我已经使用以下代码解决了它: HTML 视图:

        <table id="categoryTable" class="table table-striped table-hover">
        <tr class="header">
            <th>
                @Html.DisplayNameFor(model => model.Category)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.SubCategory)
            </th>
            <th></th>
        </tr>

        @if (Model != null)
        {
            int i = 1;
            foreach (var item in Model)
            {

                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Category)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.SubCategory)
                    </td>
                    <td>
                        <div class="col-md-10">
                            <input type="hidden" id="varIteration" value="@i" />
                            @Html.DropDownListFor(m => item.Category, new SelectList(db.Category.Where(x => !x.IsDeleted), "CategoryId", "Name"), "Select Your Category", htmlAttributes: new { @class = "form-control Category", @id = "Category" + i })
                        </div>
                    </td>
                    <td>
                        <div class="col-md-10">
                            <input type="hidden" id="SubCategoryID_CategoryID_initial" value="@item.SubCategory" />
                            @Html.DropDownListFor(m => item.SubCategory, new SelectList(db.SubCategory.Where(x => !x.IsDeleted), "SubCategoryId", "Name"), "Select Your Subcategory", htmlAttributes: new { @class = "form-control", @id = "SubCategory" + i })
                        </div>
                    </td>


                    <td>
                        @Html.ActionLink("    ", "UnifiedAccessCategoryIndex", new { Category = item.Category, Subcategory = item.SubCategory }, new { @class = "fa fa-edit fa-lg" })
                        @*<button type="submit" class="btn">

                                <i class="fa fa-check"> Update</i>
                            </button>*@
                        @*<input type="submit" value="Save" class="fa fa-check" />*@
                    </td>
                </tr>
                i++;
            }
        }

    </table>

在我的 JS 代码中:

$(document).ready(function (e) {
    var iteration = null;
    getSubCat(true, $('[class^=SubCategoryID_CategoryID_initial]').val(), iteration);
    $(document).on("change", 'select[id^=Category]', function (event) {
        iteration = $(this).closest("td").find("#varIteration").val();
        getSubCat(false, $('#Category' + iteration).val(), iteration);
    });
});
function getSubCat(load, changed, iteration) {
    var url = "/auc.accesscontrol/profiles/GetSubCatIDByCatID";

    var initialSubCat = $('[id^="SubCategoryID_CategoryID_initial"]').val();
    var initialCat = $('[id^="SubCategoryID_SubCategoryID_initial"]').val();
    if (load) {

        $('#Category' + iteration + ' option[value="' + initialCat + '"]').prop("selected", true);
    }
    if (initialCat == null) {
        changed = $('#Category' + iteration).val();
    }
    $.getJSON(url, { id: changed }, function (data) {
        $('#SubCategory' + iteration).empty();
        $('#SubCategory' + iteration).append("<option value= '0'>Select Your Subcategory</option>");
        $.each(data, function (index, item) {
            $('#SubCategory' + iteration).append("<option value='" + item.SubCategoryId + "'>" + item.Name + "</option>");
            $('#SubCategory' + iteration + ' option[value="' + initialSubCat + '"]').prop("selected", true);
        });
    });
};

【讨论】:

    猜你喜欢
    • 2011-10-29
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多