Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table if the tbody does not contain any tr.

$(document).ready(function() {
  var tbody = $(".table-condensed tbody");
  if (tbody.children().length == 0) {
    $(".blankdata").css("display", "none");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered table-condensed">
  <thead>
    <tr>
      <th class="text-center blankdata">EMPLOYEE NAME</th>
      <th class="text-center blankdata">DESCRIPTION</th>
      <th class="text-center blankdata"># of Payments</th>
      <th class="text-center blankdata">LOAN AMOUNT</th>
      <th class="text-center blankdata">TOTAL PAYMENT</th>
      <th class="text-center blankdata">BALANCE</th>
      <th></th>
    </tr>
  </thead>
  <tbody class="table-warehouse">
    <tr id="blank">
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center"></td>
    </tr>
  </tbody>
</table>

Answer №1

Consider the following:

if (!$('.table-condensed tbody tr').length)

Answer №2

Your code is correct. Simply modify the condition to !== temporarily to verify your css property.

The if condition is failing because you have a tr inside of it. By removing the tr, the if condition will execute properly. As a solution, you can change it to !== temporarily to validate it.

$(document).ready(function() {
  var tbody = $(".table-condensed tbody");
  if (tbody.children().length !== 0) {
    $(".blankdata").css("display", "none");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered table-condensed">
  <thead>
    <tr>
      <th class="text-center blankdata">EMPLOYEE NAME</th>
      <th class="text-center blankdata">DESCRIPTION</th>
      <th class="text-center blankdata"># of Payments</th>
      <th class="text-center blankdata">LOAN AMOUNT</th>
      <th class="text-center blankdata">TOTAL PAYMENT</th>
      <th class="text-center blankdata">BALANCE</th>
      <th></th>
    </tr>
  </thead>
  <tbody class="table-warehouse">
    <tr id="blank">
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center blankdata"></td>
      <td class="text-center"></td>
    </tr>
  </tbody>
</table>

Answer №3

To determine whether there is no <tr> tag within the <tbody>, you can utilize the find() function in Jquery:

$(document).ready(function() {
  var tbody = $(".table-condensed tbody");
  if (tbody.find("tr").length == 0) {
    $(".blankdata").css("display", "none");
  }
});

However, based on your example, a <tr> element does exist inside the <tbody>, so the length will not be 0.

Furthermore, if the <tr> tag is absent, it would not be possible to modify its css properties.

Answer №4

Here is how you can accomplish this:


  if($(".table-condensed tr").length==0))
    $(".table-condensed tr").css("display", "none");

Answer №5

Update the if statement to check for an empty table

if($('.table-warehouse').html().replace(/ /g,'') == '')

JSfiddle Link

Answer №6

Your current markup is not resulting in a true condition because you are placing the tr inside the tbody, which means that the

if (tbody.children().length == 0)
statement is evaluating to false. I have confirmed that the tbody is indeed empty and it is functioning correctly for me:

<table class="table table-bordered table-condensed">
  <thead>
    <tr>
      <th class="text-center blankdata">EMPLOYEE NAME</th>
      <th class="text-center blankdata">DESCRIPTION</th>
      <th class="text-center blankdata"># of Payments</th>
      <th class="text-center blankdata">LOAN AMOUNT</th>
      <th class="text-center blankdata">TOTAL PAYMENT</th>
      <th class="text-center blankdata">BALANCE</th>
      <th></th>
    </tr>
  </thead>
  <tbody class="table-warehouse">

  </tbody>
</table>

Answer №7

Below is the revised code based on your HTML:


    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <style>
    table {
        font-family: Arial, sans-serif;
        border-collapse: collapse;
        width: 100%;
    }

    td, th {
        border: 1px solid #dddddd;
        text-align: left;
        padding: 8px;
    }

    tr:nth-child(even) {
        background-color: #dddddd;
    }
    </style>
    </head>
    <body>

        <table class="table table-bordered table-condensed">
           <thead>
              <tr>
                 <th class="text-center blankdata">EMPLOYEE NAME</th>
                 <th class="text-center blankdata">DESCRIPTION</th>
                 <th class="text-center blankdata"># of Payments</th>
                 <th class="text-center blankdata">LOAN AMOUNT</th>
                 <th class="text-center blankdata">TOTAL PAYMENT</th>
                 <th class="text-center blankdata">BALANCE</th>
                 <th></th>
              </tr>
           </thead>
           <tbody class="table-warehouse">
              <tr id="blank">
                 <td class="text-center blankdata"></td>
                 <td class="text-center blankdata"></td>
                 <td class="text-center blankdata"></td>
                 <td class="text-center blankdata"></td>
                 <td class="text-center blankdata"></td>
                 <td class="text-center blankdata"></td>
                 <td class="text-center"></td>
              </tr>
           </tbody>
        </table>

    </body>

    <script type="text/javascript">
    $(document).ready(function() {
        var applyclass = true;
        var tbody = $(".table-condensed tbody");
        tbody.find('td').each(function() {
            var str = $(this).html();
            if($.trim(str) != ''){
                applyclass = false;
            }
       }) ; 
        if(applyclass){
           $(".blankdata").css("display", "none");
        }
    });  
    </script>
    </html>

Please feel free to test it out and let me know if you need any further assistance.

Answer №8

Make sure to place this script in the footer after your jQuery link. It will display alerts based on the number of rows in the table and is functioning correctly!

<script type="text/javascript>
    var rowCount = $('.table-condensed .table-warehouse tr').length;

    if( rowCount == 0){
        alert("There are no rows in the table body.");
    }else{
        alert("The table body contains rows.");
    }
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to create animated effects for hidden input fields

The struggle to smoothly animate and fade in a hidden text field can be witnessed in this example. The goal is to seamlessly move all elements around the text field and button while fading in/out the hidden element. However, it appears that towards the en ...

Issue with running CONCAT in query

I currently have: two different input options for searching. One is a text field where users can enter city, state, zip code, and type of business. The other is a drop-down menu where they can select the type of business they are looking for. My goal is ...

Transforming a flat TypeScript array into a nested object structure

I'm working on implementing a user interface to offer a comprehensive overview of our LDAP branches. To achieve this, I plan to utilize Angular Materials Tree as it provides a smooth and intuitive browsing experience through all the branches (https:// ...

Troubleshooting Issue with InfoWindow Display on Multiple Markers in Google Maps

I'm having trouble getting my markers to show different infowindows. No matter what I do, the markers always display the content of the last "contentString" in the loop. Despite reading through multiple posts on this issue, I haven't been able t ...

Step-by-step guide to implementing a sticky header while scrolling

How can I implement a fixed header on scroll, like the one seen on this website: www.avauntmagazine.com Here is the HTML for my header: <div class="bloc bgc-wild-blue-yonder l-bloc " id="bloc-1"> <div class="container bloc-sm"> &l ...

Form Automatically Submits Data Upon Loading of Page

I am currently facing an issue with my hidden div that is being loaded when I click the submit button. The form is sending results upon page load, and even though I have included the validateForm() function and called it at the end of the submit function ...

The navigation bar on the website highlights vibrant green arrows next to the

I'm having trouble implementing a bootstrap menu on my website using the code provided by Bootstrap. The menu is not displaying correctly and instead showing small green UL arrows. I have JavaScript and Bootstrap scripts in my project. Is there a way ...

Is it possible to verify if a string in JavaScript contains both numbers and special characters?

I created this function to check if a string contains numbers and special characters, but it seems to not be working correctly let validateStr = (stringToValidate) => { var pattern = /^[a-zA-Z]*$/; if (stringToValidate&& stringToValidate.leng ...

jQuery AJAX request delivering duplicate data

My jQuery ajax call is loading some elements into a div, but I am facing an issue where it returns duplicated responses. Instead of getting two elements as expected, I receive four (the 2 correct items, duplicated once). Below is the code snippet of my aj ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Tips for switching back and forth between two classes using jQuery?

I'm having some trouble with the toggleClass function. It doesn't seem to be working correctly for me. The image should toggle between displaying and hiding, but it only changes to hide, not back again. You can view my example here, along with t ...

Enhanced Bootstrap 4 button featuring custom design with text and image aligned on the right side, optimized for flexbox layout

I am looking to design a button-like div that features a flag image alongside the abbreviation of a country. Although I have some code in mind, it doesn't follow Bootstrap's guidelines and I am struggling to adapt it accordingly. <div cla ...

How can I utilize jQuery to save a simple text string in a mySQL database?

Seeking guidance on this jQuery code snippet: $('.bggallery_images').click(function () { var newBG = "url('" + $(this).attr('src'); var fullpath = $(this).attr('src'); var filename = fullpath.replace('im ...

Convert JSON data into a Google chart with a dynamic number of columns and arrays

Modify my variable chart which currently holds this JSON: [{ "month": "January", "values": [0, 0, 0, 0, 0, 0, 0, 0, 0] }, { "month": "February", "values": [0, 0, 0, 0, 0, 0, 0, 0, 0] }, { "month": "March", "values": [35, 3, 8, 18, ...

Moving through content on a single page

import React, { Component, useState } from "react"; import { Content, List, ListItem, Left, Right, Icon, Container, Header, Body, Button, Title, } from "native-base"; //Chapter One expor ...

A guide on extracting a JSON data with a BigInt type using TypeScript

I am facing an issue with parsing a bigint from a JSON stream. The value I need to parse is 990000000069396215. In my TypeScript code, I have declared this value as id_address: bigint. However, the value gets truncated and returns something like 9900000000 ...

The appearance of the pop-up mask is displayed at lightning speed

Check out the demo here Here is the HTML code: <div class="x"> </div> <input class="clickMe" type="button" value="ClickMe"></input> This is the JS code: $(".clickMe").click( function() { ...

Modifying the CSS class of an element does not produce the desired effect after altering its styles using JavaScript

html: <input id="myinput" class="cinput" type="image" src="http://www.foodwater.org.au/images/triple-spiral-3-small-button.jpg"/> <br><br><br><br> <button id="s">set to visible class</button> <button id="h"> ...

Is there a way to horizontally align the content in my footer section?

I am currently exploring React Material UI for the first time. The table I am working with can be found here under the "Custom pagination actions" section. Within this section, there is footer content containing buttons for rows per page, next, previous, ...

When the canvas is dragged, an item within it suddenly leaps or bounces

I've noticed that when I drag the canvas using -webkit-transform: translate(x,y), an element on the canvas jumps. Are there any suggestions for addressing this issue? ...