如果ID丢失,请使用jquery填充另一个隐藏字段中的行

if ID is missing fill the rows in another hiddenfield with jquery

本文关键字:字段 隐藏 另一个 填充 丢失 ID 请使用 jquery 如果      更新时间:2023-09-26

我有一个名为CustomPickedTableTable,这个Table有具有属性(如<td Data-question-id="5">Example</td>)的行,有些行根本没有任何属性。仅<td>example</td>.

我想能够将它们分类到不同的隐藏字段,这些是我的隐藏字段:

@Html.HiddenFor(model => model.SelectedCustomQuestions, new { @id = "SelectedQuestionsWithAttr" }) 
@Html.HiddenFor(model => model.SelectedQuestions, new { @id = "SelectedQuestionsWithNoAttr" })

我现在的代码是,所有具有属性"data-question-id"的行都被填充到SelectedQuestionsWithAttr,这是我对具有属性的行的隐藏字段。

但我希望我的Jquery代码也填充那些没有属性的行,并填充到我的SelectedQuestiosnWithNoAttr隐藏字段中。

这是使用隐藏字段填写所选问题的代码:

                var selectedQuestionsWithAttr = $("#SelectedQuestionsWithAttr");
                var currentIds = new Array();
                $("#CustomPickedTable").find("td").each(function () {
                    var clickedId = $(this).attr("data-question-id");
                    currentIds.push(clickedId);
                });
                selectedQuestionsWithAttr.val(currentIds.join(","));
                $("form").submit();
            }

有什么解决方案可以添加到我的jquery代码中吗?

提前感谢

您需要在<td>标签上添加东西才能识别它们:

<td id="noAttr@(Model.SelectedQuestions.IndexOf(variable))">

那么jQuery将是:

var $qWithAttr = $("#SelectedQuestionsWithAttr");
var $qWithoutAttr = $("#SelectedQuestionsWithNoAttr");
var currentIds = new Array();
var missingIds = new Array();
$("#CustomPickedTable td[data-question-id]").each(function () {
    currentIds.push($(this).attr("data-question-id"));
 });
$("#CustomPickedTable td:not([data-question-id])").each(function () {
    missingIds.push($(this).attr("id"));
 });
 $qWithAttr.val(currentIds.join(","));
 $qWithoutAttr.val(missingIds.join(","));
 $("form").submit();