简体   繁体   中英

How to hide parent div if custom_field is empty

I am not familiar with js or jquery but I need that to finish my "work". I want to hide parent div bubble if value of, let say, custom_field (CC_STAUS) is empty.

Below code is only a part of the rest:

<div class="bubble">
   <div class="arrow"></div>
     <div class="speach" style="width: 100%;">  CC_STATUS
  </div>
</div>

and css

.bubble { 
  overflow:hidden; 
  margin:5px 0 0 0;
}
.bubble .speach { 
  background-color:#333333; 
    color:#FFFFFF;
    padding:5px;
    margin:0; 
    font-size: 12px;
    font-family: Segoe UI;
  text-transform: lowercase; 
}
.bubble .arrow {
  margin:0 0 0 15px;
    width:0;
    height:0; 
  border-left: 0px solid transparent;
    border-right: 10px solid transparent;
    border-bottom: 10px solid #333333;
    border-top: 0;
}

To check the lenght of the CC_STATUS I have tried this code (which I simply adapted) but obviously it does not work. The bubble is always displaied no matter of it content.

$('.bubble').each(function() {
    if($(this).attr('CC_STATUS') === '' || $(this).text() === '') {
        $(this).parents('.bubble').hide();
    }
});

See jsfiddle

Thanks in advance for any (working) solution.

First of all, you forgot to load jquery.

Secondly, you didn't get the jquery traversal quite right - you were looking at the contents of the bubble, not the contents of speach. You also had an unwanted .parent in there.

Here's the solution:

$('.bubble').each(function() {
    if($(this).attr('CC_STATUS') === '' || $(this).find('.speach').text() === '') {
        $(this).hide();
    }
});

http://jsfiddle.net/v2Les/

Edit: Except that that $(this).attr bit is completely unnecessary, now that I take a closer look at it.

CC_STATUS is not an attribute of a bubble class element, so you can't use attr() . Is the 'speach' class reliable as a child of .bubble?

If so, try something like this:

$('.bubble').each(function() {
    if('.speach', $(this)).text() === '') {
        $(this).hide();
    }
}

In other words, foreach bubble, find its child classed 'speach' and if empty, hide the bubble.

Hopefully that gets you on your way.

The only problem I see with the answers so far is whitespace is not empty string.

var re = /\w/;
var s = $(".speach").text();
var result = re.test(s);
console.log(result) // false if non-whitespace characters exist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM