JustMe
JustMe

Reputation: 327

Hide the AJAX appends if there's nothing to display?

I'm having an AJAX function which loads some alerts in a HTML div if there's any. How can I hide this DIV if I don't have any alerts?

I tried:

// Hide alerts if there's nothing to display
            var some_alerts = document.getElementById("some_alerts");
            if (dataAlert() == false) {
                some_alerts.style.display = "none";
            } else if (dataAlert() == true) {
                some_alerts.style.display === "block";
            }

$.ajax({
    type: 'GET',
    headers: {
        "Authorization": token
    },
    url: domain + '/api/alerts?systemSerialNumber=' + psuNumber + '&limit=4',
    success: function (dataAlert) {
        let redVariable = "border-secondary";
        let redText = "text-secondary";
        for (i in dataAlert) {
            $('#list-alert').append(`
                <a class="list-group-item list-group-item-action" href="#list-item-${i}">${dataAlert[i]["Type"]} : ${dataAlert[i]["Unit Network ID"]}</a>  
            `)
            $('#details-alerts').append(`
                <h4 id="list-item-${i}">${dataAlert[i]["Unit Network ID"]}</h4>
                <p>${dataAlert[i]["message"]}</p>
            `)
        }
    }
});

<div class="row mt-4" id="some_alerts" style="display: none"></div>

Upvotes: 0

Views: 65

Answers (1)

Swapnil Shukla
Swapnil Shukla

Reputation: 229

Try this : Just check if dataAlert is empty then hide the div and return else. process and show the div

$.ajax({
  type: "GET",
  headers: {
    Authorization: token
  },
  url: domain + "/api/alerts?systemSerialNumber=" + psuNumber + "&limit=4",
  success: function(dataAlert) {
    var some_alerts = document.getElementById("some_alerts");

    // add this check
    if (dataAlert.length == 0) {
            some_alerts.style.display = "none";
            return false;
    }

    let redVariable = "border-secondary";
    let redText = "text-secondary";
    for (i in dataAlert) {
      $("#list-alert").append(`
                <a class="list-group-item list-group-item-action" href="#list-item-${i}">${
        dataAlert[i]["Type"]
      } : ${dataAlert[i]["Unit Network ID"]}</a>  
            `);
      $("#details-alerts").append(`
                <h4 id="list-item-${i}">${dataAlert[i]["Unit Network ID"]}</h4>
                <p>${dataAlert[i]["message"]}</p>
            `);
    }

    some_alerts.style.display = "block";
  }
});

Upvotes: 1

Related Questions