javascript - JQuery:识别表格文本框列中的重复值并突出显示文本框

标签 javascript jquery html

我正在使用 JQuery,我确信这是非常简单的事情,但我找不到解决方案。我有一个带有“数字”列的员工表,该列是可编辑的(文本框)。我想在“数字”列中找到重复项并突出显示这些文本框。例如,在下表中,我想突出显示所有值为 10 和 20 的文本框。此外,当编辑完成并且不再有重复项时,删除突出显示。

这是 JSFiddle

有什么想法吗?

<table id="employeeTable">
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Number</th>        
    </tr>
    <tr>
        <td>1</td>
        <td>John</td>
        <td>10</td>        
    </tr>
    <tr>
        <td>2</td>
        <td>Sally</td>
        <td>20</td>        
    </tr>
    <tr>
        <td>3</td>
        <td>Mary</td>
        <td>10</td>        
    </tr>
    <tr>
        <td>4</td>
        <td>Sam</td>
        <td>30</td>        
    </tr>
    <tr>
        <td>5</td>
        <td>Chris</td>
        <td>20</td>        
    </tr>
</table>

最佳答案

有不同的可能性,基本上你必须测试数组的值是否存在不止一次,例如像这样。

更新: 使用值选择器在初始状态下工作正常,但似乎当用户直接输入或调用 .val() 更改值时,HTML 属性 value 不会更改(只有原生 JS .value)。因此 - 要在此上下文中使用值选择器,html 值属性始终使用 JS .value 进行更新。

function highlightDuplicates() {
    // loop over all input fields in table
    $('#employeeTable').find('input').each(function() {
        // check if there is another one with the same value
        if ($('#employeeTable').find('input[value="' + $(this).val() + '"]').size() > 1) {
            // highlight this
            $(this).addClass('duplicate');
        } else {
            // otherwise remove
            $(this).removeClass('duplicate');
        }
    });
}


$().ready(function() {
    // initial test
    highlightDuplicates();

    // fix for newer jQuery versions!
    // since you can select by value, but not by current val
    $('#employeeTable').find('input').bind('input',function() {
        $(this).attr('value',this.value)
    });

    // bind test on any change event
    $('#employeeTable').find('input').on('input',highlightDuplicates);
});

Updated fiddle is here .

关于javascript - JQuery:识别表格文本框列中的重复值并突出显示文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33024381/

相关文章:

javascript - 使用扩展程序移动 chrome 窗口

javascript - FormPanel 上的按钮未显示

javascript - 如何导出多个类方法

javascript - 从更改事件中触发更改事件

javascript - 该对象引用在 $.each 中不起作用

Javascript 将 30 或 20、22 天添加到原始日期?

从另一个函数调用时,Javascript 函数返回未定义

javascript - jQuery 是否可以连接两个选择器变量?

html - 拒绝在帧中显示 'https://www.youtube.com/watch?v=oKZRsBjQJOs',因为它将 'X-Frame-Options' 设置为 'sameorigin'

html - 显示 :inline-block blocks word-wrap:break-word