Skip to content
Advertisement

I need to check if any in a html table is empty/null as in after the page loads it only returns and change it to $0

example of the table

        <table class="tg">
            <thead>
                <tr>
                    <th class="tg-0lax" id="blank-spaces"></th>
                    <th class="titles" id="this">????</th>
                    <th class="titles">???<br></th>
                    <th class="titles">???</th>
                    <th class="titles">???</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                   <td></td>
                   <td>not empty do nothing</td>
                   <td></td>
                </tr>
            </tbody>
        <table>

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

var empty = $("td").trim().filter(function () { return this.value.trim() === null })
empty.addClass("errorDefault");

if ($("td").hasClass("errorDefault")) {
    this.val("$0");
    this.text("$0");
    this.html("<p>There was an error getting data</p>");
}

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

$("tbody td")
  .filter((_, td) => !td.textContent.trim().length)
  .addClass("errorDefault")
  .text("$0");
.errorDefault {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tg">
  <thead>
    <tr>
      <th class="tg-0lax" id="blank-spaces"></th>
      <th class="titles" id="this">????</th>
      <th class="titles">???<br></th>
      <th class="titles">???</th>
      <th class="titles">???</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>not empty do nothing</td>
      <td></td>
    </tr>
  </tbody>
  <table>

If it is truly empty, CSS can do it.

tbody td:empty{
  background: red;
}

tbody td:empty:after {
  content: "$0";
}
<table class="tg">
  <thead>
    <tr>
      <th class="tg-0lax" id="blank-spaces"></th>
      <th class="titles" id="this">????</th>
      <th class="titles">???<br></th>
      <th class="titles">???</th>
      <th class="titles">???</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>not empty do nothing</td>
      <td></td>
    </tr>
  </tbody>
  <table>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement