user3066006
user3066006

Reputation: 149

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

Upvotes: 1

Views: 1283

Answers (5)

Mahmood Rehman
Mahmood Rehman

Reputation: 4331

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>

Upvotes: 2

rajesh kakawat
rajesh kakawat

Reputation: 10896

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";
 }

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

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>

Upvotes: 1

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

InnerHTML is working fine:

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

Here is working demo

Upvotes: 1

Amit
Amit

Reputation: 3289

Use isset() instead of empty() :)

Upvotes: 1

Related Questions