0

I have a table.and I need to check the table has at-least one value.and if the text in the table named Test set some alert

my table structure is

<table id="chk-table">
<tbody>
<tr>
<td>Check 
</td>
</tr>
<tr>
<td>Test
</td>
</tr>
<tr>
<td>Check1
</td>
</tr>
</tbody>
</table>

I tried something tlke

if ($('#chk-table tr').length >0) {
            if ($('#chk-table td:contains("Unknown")')) {
                alert("Test");
            }
        }

but when the table has no value the alert is showing Can anyone help?

7
  • By values do you mean text? Because the way you're doing it will alert as long as there's a <tr> tag, even if there's no text within it. You should try if ($("#chk-table tr").text() != "") { Commented Jun 6, 2014 at 12:55
  • @Coh3n yes I mean text Commented Jun 6, 2014 at 12:56
  • How do you determine/identify (valid) values? Commented Jun 6, 2014 at 12:56
  • 1
    what is #body_ctl99_lstWasteMaterial ? Commented Jun 6, 2014 at 12:57
  • 1
    A jQuery selector ($('#chk-table td:contains("Unknown")')) always returns a jQuery object; because it returns an object this is a 'truthy' value therefore the if assessment always evaluates to true. Commented Jun 6, 2014 at 13:02

2 Answers 2

3

You need a .length on the end of your selector if you are testing if it exists:

if ($('#chk-table td:contains("Unknown")').length) {
    alert("Test");
}

Example

Sign up to request clarification or add additional context in comments.

1 Comment

if the given string match any where it will be matched
1

Try:

if ($('#chk-table tr').text().trim() != "") {
    alert("Test");
}

That should alert if there is any text in any of the table's <tr> tags.

1 Comment

it would be better if you use $('#chk-table tr').text().trim()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.