Gad
Gad

Reputation: 35

How to hide a div when it contains no value with jquery

Good morning all!

I have a little problem with my shopping chart. When a user adds an element to it, the price of the item is displayed without page reload on top of the chart icon. Now I tried wrapping it in a container that I gave a background colour and some padding. that is where my issue comes in. the padding causes the div to be slightly visible before any item is added to it. so I have a little scare at the top of my shopping cart all the time.

I want to hide that div completely when it is empty (when user has not added any item/money to it)

I have come up with this code so far :

HTML

<span id ="check">
 <a href="#" class="pjCsCheckout">$70</a>
</span>

css

#check a {
  position: absolute;
  background: #ddd;
  width:auto;  
  padding: 10px;
}

Jquery

$( document ).ready(function() {
  $(function() {
    $('.pjCsCheckout').each(function() {
      if ($.trim($(this).html()) == '')
         $('.pjCsCheckout').hide();
    });
  });
});

here is a link to it : http://jsfiddle.net/u1zLbjrn/11/

thank you!!

Upvotes: 0

Views: 888

Answers (2)

Quagaar
Quagaar

Reputation: 1287

You can do this using CSS:

#check a:empty {display: none;}

Note, however, that :empty doesn't mean visibly empty but empty based on the DOM, that is, it only applies if the element contains nothing at all (with the exception of HTML comments), not even visibly empty text nodes (e.g. line break or white space). See here for more info.

If #check a contains a child element, the above style won't work. In this case, you'll have to extend the selector:

#check a span:empty {display: none;}

Note that this only hides the span inside the a element and since the padding is on a, the above style alone won't solve your problem. You also have to move the padding from a to the inner span.

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44107

Here's how you'd do it:

$(function() {
    function divCheck() {
        if ($(".pjCsCheckout").innerHTML == "") {
            $("#check").css("display") = none;
        }
    }
});

Call this divCheck function inside the onchange attribute of all your form elements, like this:

<input type="checkbox" onchange="divCheck()">

And it will work!

Upvotes: 0

Related Questions