b0y
b0y

Reputation: 576

How to toggle visibility of span on depend on content of tbody

I am using a table to populate data in tbody, also i am showing a span. The data is coming dynamically using Javascript. The dependency is something like this:

if tbody empty : display SPAN

if tbody has data : hide SPAN

// HTML code

<table id="incidents">
    <tbody>
    </tbody>
</table>
<br />
<button onclick="func()">Check table</button>
<br />

<span class="abc">Drop your files here to upload</span>

// Jquery code

function func() {
var tbody = $("#incidents tbody");

if (tbody.children().length != 0) {
      $('.abc').css('display','none');
    }
}

Upvotes: 0

Views: 97

Answers (3)

Mahesh.D
Mahesh.D

Reputation: 1689

Use trim as additional check

function func() {
  var contentLen = $.trim($("#incidents tbody").children()).length;

  if (contentLen == 0) {
   $('.abc').css('display','none');
  } else {
   $('.abc').css('display','block');
  }    
}

Upvotes: 1

guradio
guradio

Reputation: 15555

function func() {
  var tbody = $("#incidents tbody");

  if (tbody.children().length == 0) {
    $('.abc').removeClass('hide');
  }
}
.hide {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="incidents">
  <tbody>
  </tbody>
</table>
<br />
<button onclick="func()">Check table</button>
<br />

<span class="abc hide">Drop your files here to upload</span>

function func() {
  var tbody = $("#incidents tbody");

  if (tbody.children().length == 0) {
    $('.abc').removeClass('hide');
  }
}
.hide {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="incidents">
  <tbody>
    <tr><td>asd</td></tr>
  </tbody>
</table>
<br />
<button onclick="func()">Check table</button>
<br />

<span class="abc hide">Drop your files here to upload</span>

  1. check if tbody children length is == 0
  2. better to just add/remove class than directly putting css using jquery/js

Upvotes: 0

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

Try this

if($("#incidents tbody").children().length > 0)
{
  $('.abc').css('display','none');
} 
else 
{
  $('.abc').css('display','block');
}

Upvotes: 0

Related Questions