0

I have this html table (vastly simplified to protect the innocent)...

<table id="codeList">
<thead> 
    <tr>
        <th>Code</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Code1 <input type="hidden" name="code1" value="123"/></td>
    </tr>
        <tr>
        <td>Code2 <input type="hidden" name="code2" value="456"/></td>
    </tr>
    <tr>
        <td>Code3 <input type="hidden" name="code3" value="789"/></td>
    </tr>
</tbody>

...and I'm trying to determine in a javascript method if the code is already in the table...

if (!$('#codeList >tbody').is( ":contains('456')")) {
    $("#codeList > tbody:last").append("<tr>" +
    "<td> Code2 <input type='hidden' name='code2' value='456'/></td>" +
    "</tr>");
}

...which isn't working. Basically, I need a JQuery expression that can search the rows of the table, checking the value of each hidden field to see if it already exists and return true/false, or at least behave like true/false for the purposes of a javascript conditional. This is a bit different from most scenarios that I see in that I need to determine if a row doesn't exist and then act on the table. Most people want to select rows that DO exist and then act on them.

3 Answers 3

2

Don't use :contains for attribute values, use the attribute equals selector:

if (!$('#codeList input[value="456"]').length) {
   // do something
}

That is select any inputs with that value that are descendents of #codeList and if none are found then .length will be 0...

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

Comments

0
if (!$("#codeList input[value='456']")[0]) {
    $("#codeList > tbody:last").append("<tr>" +
    "<td> Code2 <input type='hidden' name='code2' value='456'/></td>" +
    "</tr>");
}

Comments

0
if (!$('#codeList input[value="456"]').length) {
 $("#codeList > tbody:last").append("<tr>" +
  "<td> Code2 <input type='hidden' name='code2' value='456'/></td>" +
  "</tr>");
}

Comments

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.