使用Jquery过滤器检查重复列数据

3
请注意,我的前两个表格数据(苹果和橙子)被设置为只读。而且我有一个用于动态添加行的函数。 请参见演示FIDDLE
如果用户点击“保存”按钮,则所有检测到与数据库中的数据或最后一行动态添加的重复数据的输入字段的边框颜色将变为红色。
$("#save").off("click").on("click",function(){
var $rows = $('#myTable tbody tr:not(:hidden)');
        $rows.each(function(){
        var $id = $(this).find('td input[type=\'text\']');
            alert($id.val());
        //Im stuck here, for checking column data is duplicate.
      });
});

我希望使用像这样的jQuery过滤器,例如:

$( "li" ).filter( "DUPLICATE DATA()" ).css( "border-color", "red" );

2
你的意思是要确保没有多行具有相同的“名称”吗? - jvanstry
1个回答

4

我假设你想要针对“Name”列进行操作,尽管你可以很容易地改变它来操作所有列。

基本上,你需要遍历input元素,并保持对已经审核过的值的引用:

$("#save").off("click").on("click",function(){
    var existing = [];
    var duplicates = $('#myTable td:nth-child(3) input').filter(function() {
        var value = $(this).val();
        if (existing.indexOf(value) >= 0) {
            return $(this);
        }
        existing.push(value);
    });
    duplicates.closest('tr').css('background-color', 'red');
});

JSFiddle

编辑:为了避免将只读行标记为重复行,此过程相对复杂一些。

$("#save").off("click").on("click",function(){
    // Clear status of all elements
    $('#myTable tr').css('background-color', 'none');

    // Get all values first (Apple, Orange, etc) as strings
    var allValues = $('#myTable td:nth-child(3) input').map(function() {
        return $(this).val();
    }).toArray();

    // Iterate unique values individually, to avoid marking a read-only input as duplicate
    var processedValues = [];
    for (var i = 0; i < allValues.length; i++) {
        var value = allValues[i];
        if (value != '' && processedValues.indexOf(value) >= 0) continue;
        var inputs = $('#myTable td:nth-child(3) input').filter(function() { return $(this).val() == value; });
        // Check if this value is in one of the readonly
        var readOnlyInput = inputs.filter(function() { return $(this).is('[readonly]'); });
        if (readOnlyInput.length) {
            inputs.not(readOnlyInput).closest('tr').css('background-color', 'red');
        } else {
            inputs.not(':first').closest('tr').css('background-color', 'red');
        }
        processedValues.push(value);
    }
});

Updated JSFiddle


td:nth-child(3) input 在IE上不起作用,我猜测。你能帮我解决一下吗,使用上面发布的代码。谢谢 :) - bumbumpaw
1
td:nth-child 在旧版本的IE中可能无法正常工作,因为您使用的是jQuery版本2.1。请访问jQuery下载页面了解更多关于浏览器支持和适合您的版本的信息。 - cypherkaz
当你在中间有一个空行时,出现了奇怪的行为。我的错,我试图用return而不是continue跳过处理空值。已更新答案 :) - cypherkaz
请看这个链接:http://stackoverflow.com/questions/26967468/trying-to-catch-another-condition-for-boolean-false-value - bumbumpaw
看到了你的问题。我相信你正在尝试确定在处理过程中是否找到了某个特定值超过一次。你正在查找错误的代码部分(if (readOnlyInput.length) 只会告诉你标记为只读输入的数量对于该特定值)。请查看 fiddle - cypherkaz
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接