user1527762 user1527762 - 8 days ago 5
HTML Question

JQuery: Identify duplicate values in a table textbox column and highlight the textboxes

I'm using JQuery and I'm sure this is pretty simple stuff but I was unable to find a solution. I have an employee table with "Number" column which is editable(text box). I want to find the duplicates in the "Number" column and highlight those textboxes. For example in the table below I want to highlight all textboxes with values 10 and 20. Also when a edit is done and there are no longer duplicates, remove the highlight.

Here's the JSFiddle

Any Ideas?

<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>

Answer

There are different possibilities, basically you'll have to test if the value of an array exists more than one time, for example like this.

Update: Using the value selector works fine in the initial state, but it seems that when a value is changed by direct user input or by calling .val(), the HTML attribute value is not changed (only the native JS .value). Therefore - to use the value selector in this context, the html value attribute is always updated with the 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.

Comments