example of the table
JavaScript
x
19
19
1
<table class="tg">
2
<thead>
3
<tr>
4
<th class="tg-0lax" id="blank-spaces"></th>
5
<th class="titles" id="this">????</th>
6
<th class="titles">???<br></th>
7
<th class="titles">???</th>
8
<th class="titles">???</th>
9
</tr>
10
</thead>
11
<tbody>
12
<tr>
13
<td></td>
14
<td>not empty do nothing</td>
15
<td></td>
16
</tr>
17
</tbody>
18
<table>
19
Now the way this is really written, data will be pushed into each td from an API, some times that API is down, and I would like to use jquery to check if a td has anything displaying in it and if it doesnt I want there to be a string with an error message in the td. This is the jquery im trying currently
JavaScript
1
9
1
var empty = $("td").trim().filter(function () { return this.value.trim() === null })
2
empty.addClass("errorDefault");
3
4
if ($("td").hasClass("errorDefault")) {
5
this.val("$0");
6
this.text("$0");
7
this.html("<p>There was an error getting data</p>");
8
}
9
Advertisement
Answer
- There is no .trim() in jQuery
- string trim() is not going to return null.
- table cells do not have value
- $(“td”).hasClass(“errorDefault”) only looks at first element
JavaScript
1
4
1
$("tbody td")
2
.filter((_, td) => !td.textContent.trim().length)
3
.addClass("errorDefault")
4
.text("$0");
JavaScript
1
3
1
.errorDefault {
2
background-color: red;
3
}
JavaScript
1
19
19
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<table class="tg">
3
<thead>
4
<tr>
5
<th class="tg-0lax" id="blank-spaces"></th>
6
<th class="titles" id="this">????</th>
7
<th class="titles">???<br></th>
8
<th class="titles">???</th>
9
<th class="titles">???</th>
10
</tr>
11
</thead>
12
<tbody>
13
<tr>
14
<td></td>
15
<td>not empty do nothing</td>
16
<td></td>
17
</tr>
18
</tbody>
19
<table>
If it is truly empty, CSS can do it.
JavaScript
1
7
1
tbody td:empty{
2
background: red;
3
}
4
5
tbody td:empty:after {
6
content: "$0";
7
}
JavaScript
1
18
18
1
<table class="tg">
2
<thead>
3
<tr>
4
<th class="tg-0lax" id="blank-spaces"></th>
5
<th class="titles" id="this">????</th>
6
<th class="titles">???<br></th>
7
<th class="titles">???</th>
8
<th class="titles">???</th>
9
</tr>
10
</thead>
11
<tbody>
12
<tr>
13
<td></td>
14
<td>not empty do nothing</td>
15
<td></td>
16
</tr>
17
</tbody>
18
<table>