Bradie Bradie - 3 months ago 23
HTML Question

Hide text boxes if it does not contain data

I am trying to use javascript to hide a table if there is no data present. I am using Powershell to grab data from a spreadsheet; however, if there is no data in the spreadsheet the table is not required.

In a nutshell, if the td with an id of "hide if empty" does not contain any data can the div with div with id "sampleDIV" or the table with id "Tabletest" not be visible?

Is this possible?

Thank you :)



<div id="SampleDIV">
<table id="TableTest">
<tbody>
<tr>
<td><b>Data:</b></td>
<td id="hide if empty"></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>





Am I doing something really silly?



<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>

<script language ="javascript">
if (document.getElementById("hideifempty").innerHTML === "") {
document.getElementById("SampleDIV").style.display = "none";
}
</script>
</head>
<div id="SampleDIV">
<table id="TableTest">
<tbody>
<tr>
<td><b>Data:</b></td>
<td id="hideifempty"></td>
<td></td>
</tr>
<tr>
<td></td>
<td>If you can see this it didn't hide</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<body>
</body>
</html>




Answer

if (document.getElementById("hideifempty").innerHTML === "") {
  document.getElementById("SampleDIV").style.display = "none";
}
<div id="SampleDIV">
  <table id="TableTest">
	<tbody>
        <tr>
        <td><b>Data:</b></td>
        <td id="hideifempty"></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td>If you can see this it didn't hide</td>
        <td></td>
      </tr>
    </tbody>
  </table>
</div>

You may want to use .innerHTML.trim() === "" - up to you depending on whether you define an element with nothing but whitespace as "empty".

Note: Element IDs are not supposed to contain spaces (although that may work in some browsers), so I've changed the id to "hideifempty".

EDIT: Note that the above JS would need to be in a <script> element that is after the <div> in question, so e.g., you could follow the reasonably standard practice of putting scripts immediately before the closing </body> tag. Or you could wrap the above if statement in an onload or DOMContentLoaded handler. Otherwise the JS will run before the browser has parsed the div and table.