Home > OS >  I need to check if any <td> in a html table is empty/null as in after the page loads it only r
I need to check if any <td> in a html table is empty/null as in after the page loads it only r

Time:02-15

example of the table

        <table >
            <thead>
                <tr>
                    <th  id="blank-spaces"></th>
                    <th  id="this">????</th>
                    <th >???<br></th>
                    <th >???</th>
                    <th >???</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>");
}

CodePudding user response:

  • 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 >
  <thead>
    <tr>
      <th  id="blank-spaces"></th>
      <th  id="this">????</th>
      <th >???<br></th>
      <th >???</th>
      <th >???</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 >
  <thead>
    <tr>
      <th  id="blank-spaces"></th>
      <th  id="this">????</th>
      <th >???<br></th>
      <th >???</th>
      <th >???</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>not empty do nothing</td>
      <td></td>
    </tr>
  </tbody>
  <table>

  • Related