Hobby99
Hobby99

Reputation: 703

Hide div when no mysql value retrieved

I found several solutions for hiding divs when they are empty but not in connection with a mysql retrieved value.

<button class="platform_category" id="platform_', $platform['platform_id'],'_category"><a href="', $platform['platform_url'],'" target="_tab">', $platform['platform_category1'],'</a></button>

Jquery does not hide div when there is no data in mysql-row because it thinks $platform['platform_category1'] is a value even though that is only the php-code to retrieve the mysql value in case there is one.

For the hiding jquery code I am using this:(if I replace the == with != it hides)

    $(function() {
    $('.platform_category').each(function() {
        if ($(this).html() == "") {
             $(this).hide();
       }
    }); 
});

Upvotes: 1

Views: 308

Answers (4)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

I would use filter to check the content of the .platform_category. See below,

$(function() {
   $('.platform_category').filter(function() {
       return $.trim($(this).text()) == '';
    }).hide();
});

Upvotes: 1

Brian Hoover
Brian Hoover

Reputation: 7991

The problem is that $('.platform_category') isn't actually empty, because there is always an anchor tag in the div.

You could do this two ways, either via PHP (the best) or via JavaScript

Via PHP

   if ($platform['platform_category1'] != "") {
     <button class="platform_category" id="platform_', $platform['platform_id'],'_category">
        <a href="', $platform['platform_url'],'" target="_tab">',$platform['platform_category1'],'</a>   
      </button>

If you have to do it via JavaScript

    $(function() {
    $('.platform_category').each(function() {
        if ($(this).find('a').html() == "") {
             $(this).hide();
       }
    }); 
});

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

$('.platform_category').each(function() {
    if ($.trim( $(this).text() )  ==  "") {
        $(this).hide();
    }
});

Upvotes: -1

VisioN
VisioN

Reputation: 145408

Buttons with class platform_category have <a> tag as inner html, so html() method does not make any sense here (it will always return <a>). Try text() instead:

$('.platform_category').each(function() {
    if ($(this).text() == "") {
        $(this).hide();
    }
});

GOOD NOTE (from @Blazemonger): It is good to use text trimming with $.trim() method:

if ($.trim($(this).text()) == "") {
    $(this).hide();
}

Upvotes: 2

Related Questions