...">

JavaScript hides DIV tag if text is 0

I have a problem. I am trying to hide a div if the text is 0. My code:

<script type="text/javascript">
    $(function () {
        if ($(".notification-counter").text() == "0") {
            $(".notification-counter").hide();
            $(".notification-container").hide();
        }
    });
</script>

<div class="dropdown nav-search pull-right <?php $this->_c('login') ?>">
    <a href="../pm/" class="dropdown-toggle"><i class="fa fa-inbox"></i>
        <div class="notification-container">
            <div class="notification-counter">
                <?php
                      jimport( 'joomla.application.module.helper' );
                      $module = JModuleHelper::getModule('mod_uddeim_simple_notifier');
                      echo JModuleHelper::renderModule( $module, $attribs );
                ?>
            </div>
        </div>                                  
    </a>    
</div>

but it doesn't work ... can anyone help? thanks for answers!

+4
source share
5 answers

Try using parseInt()to compare your number with a number rather than comparing text strings (this alleviates problems with spaces. JSFIDDLE

$(function () {
    if (parseInt($(".notification-counter").text()) == 0) {
        //$(".notification-counter").hide();
        $(".notification-container").hide();
    }
});
+4
source

Use cropping as there are spaces

Fiddle

$(function () {
    if ($.trim($(".notification-counter").text()) == "0") {
        $(".notification-counter").hide();
        $(".notification-container").hide();
    }
});
+3
source

0, .

$(function () {
    if ($(".notification-counter").text() == 0) {
        $(".notification-counter").hide();
        $(".notification-container").hide();
    }
});

: , :

 //hit F12 to view the console
var counter = $(".notification-counter");
var container = $(".notification-container");
console.log(container.text(), container.html());
console.log(container.text() == 0,container.text() == "0");
//true, false
console.log(typeof 0, typeof "0");
//number, string

JSFiddle

+2
var notificationCounter = $('.notification-counter');
if (notificationCounter.text().trim() === '0') {
  notificationCounter.closest('.notification-container').hide();
}
+1

: .text() .html()

$(function() {
  if ($(".notification-counter").html() == "0") {
    $(".notification-counter").hide();
    $(".notification-container").hide();
  }
});
+1

All Articles