JQuery:在表文本框列中标识重复值并突出显示文本框

use*_*762 2 html javascript jquery html5

我正在使用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>
Run Code Online (Sandbox Code Playgroud)

axe*_*hel 5

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

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

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);
});
Run Code Online (Sandbox Code Playgroud)

更新的小提琴在这里.