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.
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...
if (!$("#codeList input[value='456']")[0]) {
$("#codeList > tbody:last").append("<tr>" +
"<td> Code2 <input type='hidden' name='code2' value='456'/></td>" +
"</tr>");
}
if (!$('#codeList input[value="456"]').length) {
$("#codeList > tbody:last").append("<tr>" +
"<td> Code2 <input type='hidden' name='code2' value='456'/></td>" +
"</tr>");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.