Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 224
SimonDowdles Avatar asked Sep 07 '10 10:09

SimonDowdles


People also ask

How do you check if a table contains a value in jquery?

$("#table tr td:nth-child(8)"). each(function () { var texttocheck = this. innerText. trim(); if (texttocheck == "mukesh") { var errMsg = "user already exists in the list"; alert(errMsg); return false; } return false; });

How do you check if a value exists in a table JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.

How do you check if the element is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.


2 Answers

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.

like image 126
Andy E Avatar answered Oct 13 '22 00:10

Andy E


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.

like image 21
Bozho Avatar answered Oct 12 '22 23:10

Bozho