检查Javascript中现有表中的重复行输入

时间:2018-04-13 06:55:06

标签: javascript

我有一个包含多行的表,并尝试通过具有下拉选项的模态输入添加新行。如果我为新条目中的所有列输入相同的值并在模态上单击“确定”,则会将相同的行添加到表中而不是显示警告。我该如何解决?我在验证模态表单输入时尝试了以下代码,但它不起作用。

$("#validateThresholdForm").on("click", function () {
    var table = $("#thresholdAlertTable");
    var firstTd = $("td:first", table);
    var secondTd = firstTd.next();
    var thirdTd = secondTd.next();
    var fourthTd = thirdTd.next();

    if (firstTd.text() == $("#catList").val() &&
        secondTd.text() == $("#thType").val() &&
        thirdTd.text() == $("#thFrequency").val() &&
        fourthTd.text() == $("#thEmail").val())
        alert("Error: You're trying to add the same entry");

    $("#thresholdForm").validate({
        errorPlacement: function errorPlacement(error, element) { /*element.after(error);*/
        }
    });
    if ($("#thresholdForm").valid()) {
        var emails = $("#thEmail").val();
        if (validateDateRange() && validateMultipleEmailsCommaSeparated(emails)
             && validateSentimentScoreRange()
             && validateVolume()) {
            addThreshold();
        }
    } else {
        $("div.formErrorContent").removeClass("formErrorContent").addClass("alertFormError");
    }
});

1 个答案:

答案 0 :(得分:0)

您必须发布有关您的表和数据的更多信息,但假设单元格上的数据是原始数据(既不是html,也不是格式),您可以迭代它:

    var table = $("#thresholdAlertTable");
    var formValuesArray = [
        $("#catList").val(),
        $("#thType").val(),
        $("#thFrequency").val(),
        $("#thEmail").val()
    ];
    var exists = false;
    $("tr", table).each(function(rowIndex, trDomElement) {
        exists = false;
        $("tr", $(trDomElement)).each(function(cellIndex, tdDomElement) {
            // We are on cell "cellIndex" of row "rowIndex", check value with correspondent input of form
            exists = exists && (formValuesArray[cellIndex] == $(tDomElement).text();
            if (!exists) {
                // That row doesn't contain the element, we can break the bucle
                // return false to break the "each" function
                return false;
            }
        });
        if (exists) {
            // That row contains the same element, break the bucle
            // return false to break the "each" function
            return false;
        }
    });

    // at the end of code, exists variable contains the value if there's another element with the same values

它只是一个参考,您应该控制值的错误,文本的大小写......