Concealing a Bootstrap table on an ASP.NET MVC View using jQuery

My website is powered by ASP.NET MVC and it showcases records in a Bootstrap 3 table. When there are no records, a div is displayed. Following the advice of another user, I adjusted the view to render the table along with the "no records" div simultaneously.

Here's what I have in my application:

  1. In my CSS, I've set the table display property to none
  2. At the beginning of my JS file, I perform the following actions...

    var absenceRows = $("#absencesTable tbody").find("tr").length;
    
    var $absTable = $("#absencesTable");
    
    var emptyAbsenceDiv = $("#no-absences");
    
    console.log(absenceRows);
    
    if (absenceRows === 0)
    {
       emptyAbsenceDiv.show("fast");
       $absTable.hide("fast");
    }
    else
    {
       emptyAbsenceDiv.hide("fast");
       $absTable.show("fast");
    }
    
  3. Next, there is an AJAX call where data is retrieved:

     $("#chosenDate").on("dp.change", function (e) {
    
        var formattedDate = moment(e.date._d).format('DD/MM/YYYY');                    
    
        $(document).ajaxStart(function () {
            $("#absencesTable, #no-absences").fadeOut('0');
            $("#loading").show();
        });
        $(document).ajaxComplete(function () {
            $("#loading").hide();
            $("#absencesTable").fadeIn('200');
        });
    
        var ajaxOptions = {
            url: absenceDateUrl,
            type: 'post',
            contentType: 'application/json',
            dataType: 'json',
            data: '{selectedDate:' + JSON.stringify(formattedDate) + '}'
        };    
    
        $.ajax(ajaxOptions).done(function (data) {
    
            console.log(data);
            if (data !== null && data.length !== 0) {
                renderData(data);
            }
            else
            {
                console.log("No data! " + $("#absencesTable").is(":visible"));
                hideAbsences();
    
            }
        });
    });
    
  4. In the renderData function, data is constructed and then the table is shown while the no-absences div is hidden:

    $("#no-absences").hide("fast", function () {
        $("#absencesTable").show("fast");
    });
    

    This method works perfectly fine.

  5. If no data is returned, the hideAbsences() function gets triggered:

    if ($("#absencesTable").is(":visible")) {
        $("#absencesTable").hide("fast");
        $("#no-absences").show("fast");
    }
    

I am aware that checking the visibility of the table might not be necessary, but I'm trying all possibilities at this point.

However, when there is no data, my table fails to hide. Both the div and the table remain visible.

For reference, here is the snippet from my View:

    @if (Model.Count() == 0)
{
    <div class="well well-lg" id="no-absences"><h3>Everybody is in! There are no absences today :)</h3></div>
}

<table class="table table-striped table-bordered" id="absencesTable">
    <thead>
        <tr>
            <th>
                Name
            </th>
            <th>
                Date Out
            </th>
            <th>
                Return Date
            </th>
            <th>
                Absence Type
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.FullName
                </td>
                <td>
                    @item.DateFrom.Value.ToLongDateString()
                    <span class="label label-default">@item.AbsencePeriodFrom.PeriodText</span>
                </td>
                <td>
                    @item.DateTo.Value.ToLongDateString()
                    <span class="label label-default">@item.AbsencePeriodTo.PeriodText</span>
                </td>
                <td>
                    @item.AbsenceType.AbsenceTypeText
                </td>
            </tr>
        }
    </tbody>
</table>

Even though the display property of the table is set to "display:table" when data is received, I don't think that's causing the issue with show/hide functionality. I may be mistaken. My goal is simply to toggle between showing the table or the div, not both simultaneously.

Just an FYI, I attempted to replicate the error on jsFiddle, but couldn't (http://jsfiddle.net/f2r9mdah/). It seems like there might be something off with my jQuery or the View itself.

Answer №1

After countless challenges, I finally stumbled upon a solution. The strange thing is, I still can't quite comprehend why it works.

Upon selecting a date in the calendar control, an ajax call is triggered. To handle this, I enclosed my code within a try/catch block:

$("#chosenDate").on("dp.change", function (e) {

        try
        {
            console.log("$absTable = " + $absTable.is(":visible"));
            console.log("emptyAbsenceDiv = " + emptyAbsenceDiv.is(":visible"));

            var formattedDate = moment(e.date._d).format('DD/MM/YYYY');                    

            var ajaxOptions = {
                url: absenceDateUrl,
                type: 'post',
                contentType: 'application/json',
                dataType: 'json',
                data: '{selectedDate:' + JSON.stringify(formattedDate) + '}'
            };    

            $.ajax(ajaxOptions).done(function (data) {

                console.log("inside ajax done = " + data);
                if (data !== null && data.length !== 0) {
                    renderData(data);
                }
                else
                {
                    hideAbsences();
                }
            });

        }
        catch(Exception)
        {
            //throw Exception;
        }
    });

To add an extra layer of certainty, I enclosed the table within a div and toggled visibility using hide and show on the new div. Interestingly enough, introducing the div had no impact on the functionality, only the try/catch block did.

The mystery persists - why does toggling visibility of a table element alone not suffice? Could this be attributed to a Bootstrap 3 quirk, or perhaps the calendar control I'm utilizing...? If anyone has insights to share, please do enlighten me.

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

Tips on utilizing a local file as a background image URL

How can I modify my CSS to link to a local file path like C:\xampp\htdocs\Folder instead of the URL https://source.unsplash.com/1600x1050/?nature. I am currently using Bootstrap 4 and below is my CSS code: .jumbotron{ background: ...

Utilizing Javascript to filter data across multiple columns in tables

I've been experimenting with the JavaScript code below to filter table rows. The original code is from w3schools, but I made some modifications to target all input values. It works well for filtering one column, however, when I try to input a value in ...

I'm looking for a way to track the progress of an ajax call. Specifically, I want to know how I

I am currently working on an AJAX call that executes a lengthy PHP script producing 20 different results. I aim to display the progress of each step within the script, such as 1/20 complete, 2/20 complete, 3/20 complete. Last updated on 29-12-2015 at 03:1 ...

Seeking Up/Down Arrows HTML numerical input feature specifically designed for iOS devices

I am having an issue with a number input box on iOS. I am utilizing jquery, kendo mobile, and HTML5 for this particular task. While the number input displays up and down arrows in the Icenium simulator, they are not showing on the iPad. I am seeking a sol ...

Moving list elements by dragging and dropping them within table cells using jQuery

I'm currently working on a project that requires the functionality of dragging and dropping list items between table cells. This means allowing users to drag an item from one cell and drop it into another, with the new location being saved. Does anyon ...

Troubleshooting: PHP Ajax function fails to post data

I'm having an issue with my Jquery ajax function. It seems that the getinvoices value is not being passed to the PHP file, although I have other Ajax requests in the same file that work perfectly fine. This is the code I am using: Javascript $( "#up ...

Issues with HostIP.info's get_json function failing to trigger the jQuery ajax callback

I have been attempting to retrieve a user's IP address using jQuery/JSONP. I have had success with other services, but for some reason the callback is not being triggered when I use hostip.info's JSON API Both Firebug and Fiddler show that the J ...

Using jQuery Ajax to retrieve a server XML file response and storing it in a JavaScript array

I'm attempting to receive an XML response in a JavaScript array like this: <script type="text/javascript"> var arrayName = []; var arrayValue []; $(document).ready(function() { $.ajax({ type: "GET", url: "data.xml", da ...

Having trouble with my basic AJAX request; it's not functioning as expected

I am currently diving into the world of Ajax and I've hit a roadblock: 1. HTML : <body> <form> Username: <input type="text" id="username" name="username"/> <input type="submit" id="submit" /> </form> <scrip ...

Learn the process of including an active class using jQuery from an external active.js file!

This JavaScript code snippet $(function() { $("#navbar-nav li").click(function($) { // remove classes from all $("li").removeClass("active"); // add class t ...

Strange gap between element and border on chrome

I noticed some strange spacing between the div borders and elements when I wrapped a few divs inside a container. This issue is only happening on Chrome and Edge, while Mozilla seems to display it correctly. My code includes the usage of Bootstrap along w ...

Beneath the footer lies a blank space in white

Visit our site for information on various towns. However, we are facing an issue with the CSS when it comes to new or less populated towns like this one, where the footer is not aligning properly and leaving a large white gap below. We attempted to implem ...

Guide to implementing a JQuery datepicker in a basic Rails application

Being a beginner in Ruby On Rails and web programming, I am transitioning from a traditional desktop programming background. While I have created a few simple rails applications before, this is my first attempt at using Rails3 and integrating jQuery. I am ...

An advanced coding tool that is able to transfer CSS code from the style attribute to the class definition

Is there an editor or IDE that can convert styles from CSS classes to inline styles? .my_class { color: black; } <span class="my_class" style="font-size: 200%;">test</span> to .my_class { color:black; font-size: 200%; } <span ...

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

Enable or disable options with the user's permission

Currently, I am developing a WordPress plugin that will display a simple div on all pages. The code is set up to create the div, turn it into a shortcode, and then show it on each page. I want to include a checkbox in the admin settings so that users can ...

Is it necessary to use a specific button to submit on Return (Enter)?

In a wizard-type form, there are two buttons present. The Back button is positioned on the left side, while the Next button is located on the right side. For an example of this setup, visit http://jsfiddle.net/WSwb7/1/. Please note that submitting the form ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...

Exploring the Spotify API with jQuery/ajax to fetch details about songs, artists, and albums

I've been researching and have come across some information that is somewhat similar, but I'm still struggling to completely understand how this process works. My goal is to make a request to the Spotify API using jQuery to search for an artist ...

Using Font Awesome Class Aliasing

Is there a way to create an alias for a Font Awesome class like fa fa-users, and then switch between classes dynamically? I'm working on a project where I need to use Font Awesome icons, and currently I have the following code: <i class="fa fa-us ...