'jQuery: Check to see if table row containing certain values exists already

I have a jQuery script that appends a row to a table. In short, the user can select a value from a drop down menu, then enter in 'x' amount of months and hits 'add', which appends the row to the table. For example the following row is appended by the user:

<tr>
  <td>Some Value</td>
  <td>2</td>
</tr>

Now, if the user performs the same operation again, I need to stop the procedure and alert him that he is trying to add a duplicate value. How - using jQuery - can I check to see whether or not the above row already exists, where the first and second <td> elements have the same value as the data he is trying to add? The reason I say first and second <td> elements only is because there are other <td> elements in the row but they house hidden fields which submit the newly added data to to a server side script, so I'd like to keep the validation as short and simple as possible.

If it is of any help, the table ID is #tblspecializations

Many thanks for your input.



Solution 1:[1]

You might be able to use :contains():

$('#tblspecializations tr > td:contains(Some Value) + td:contains(2)').length

- Example

Be aware, though, that :contains() will return the element if the given string is matched anywhere in the text of the element.

Solution 2:[2]

I'd suggest you hold your data in some data structure (an (associative) array for example). Thus you will verify the data in the structure, rather than in the DOM.

Solution 3:[3]

To put it short, the following code in the click() handler should help you in your situation; you can see the whole code in action:

$(function(){
    $("#btn").click(function(){
        var table = $("#tblspecializations");
        var firstTd = $("td:first", table);
        var secondTd = firstTd.next();

        if(firstTd.text() == $("#dropdown").val() && secondTd.text() == $("#num").val())
            alert("Error: You're trying to add the same entry");
    });
});

Short explanation: By using td:first in the selector, you're getting the first column in your table, and by using the next() function, your getting its sibling, namely the second column.

Solution 4:[4]

if($('table').find('td').filter(function () {return this.innerHTML == '20';}).length>0){ alert("Si");}else{alert("No");}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andy E
Solution 2 Bozho
Solution 3 Giuseppe Accaputo
Solution 4 andresflorez12