简体   繁体   中英

How can I hide a Div when text of a label is empty?

I am trying to hide the 'div' by checking if a label is empty. But Something went wrong. Below is the code I used.

<script>
 function myfun(){
     if (document.getElementById('department').innerHTML=='') {
         document.getElementById('departmentdiv').style.display="none";
     }
 }
</script>
<body onload="myfun()">
  <div id="departmentdiv" class="row-fluid">
    <label>DEPARTMENT:</label>
    <label id="department"><?php if (!empty($_POST['department']))echo $_POST['department'];?></label>
  </div>
</body>

I am getting the POST[department] value from the a different page and assigned it to the label in this page. I want to show the div only if the value is not null. But, the problem is label doesn't show at all on this page even if its not null. Does anybody can help me out

May be you can try php empty function for validation .check if not empty post department then show :

<script>
    function myfun(){
    <?php if (empty($_POST['department'])){?>
        document.getElementById('departmentdiv').style.display="none";
    <?php }?>
    }
</script>

try something like this,

if (document.getElementById('department').innerHTML.length) {
    document.getElementById('departmentdiv').style.display="none";
}

if whitespace is causing problem then,

 if (document.getElementById('department').innerHTML.trim().length) {
   document.getElementById('departmentdiv').style.display="none";
 }

使用isset()代替empty() :)

InnerHTML is working fine:

 if (document.getElementById('department').innerHTML == '') {
     document.getElementById('departmentdiv').style.display = "none";
 }

Here is working demo

As you can see in this JSFiddle , it does work. The problem must be with the PHP code. You don't need to test with empty() , just output the variable. If there might be whitespace in the department, trim it before outputting

<div id="departmentdiv" class="row-fluid">
    <label>DEPARTMENT:</label>
    <label id="department"><?= trim($_POST['department']); ?></label>
</div>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM