Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 94
  • Last Modified:

Hiding divs (and content) if content empty

Hello,

I am developing a plugin to work in Visual Composer for Wordpress. I am almost ready for prime-time but having an issue with hiding divs (containing empty tags *like [$price1] )

The plugin works in a way where the user inputs the data via a small admin control panel, and where thay have added info into each section, (there are 3) the page shows them in the section where the plugin module is placed on the wordpress page - the look and feel of the plugin is controlled by a css stylesheet loaded by the plugin.

The problem I'm having is that the tags all show on  the page (which means its working - yay!) - but - even if there is no data in the tag the div container still shows, naturally as there is no "hidden" styles attached to any of them. So I tried to get the divs to not display by using an (if)

***test one
/* if( !!empty( $portion_price_two ) ) {
               echo ( '<style>.sub2{display:none;.price2{display:none;.line2{display:none;}</style>' );
            }else {
               echo ( '<style>.hide2{display:block;}</style>' );
            }*/

That did'nt work, it hid the div's content ($portion_price_two) only and not the containin div *whch has up three other tagged fields.

***test two
So I tried running a class called hide2 and hide3 and added that to each div *to control that particluar div - yes the comtent did not display but the container still did.

***test three
tried a similar approch by surrounding the entire set with a div - but the results worked the same. - dang!

--------------------

The field tags are displayed in a results html like this:

--------------------
$atts ) );
          $content = wpb_js_remove_wpautop($content, true); // fix unclosed/unwanted paragraph tags in $content

          $portion_choice_one;$portion_choice_two;$portion_choice_three;

          $currency_choice_one;$currency_choice_two;$currency_choice_three;

          $price;

          /* if( !!empty( $portion_price_two ) ) {
               echo ( '<style>.sub2{display:none;.price2{display:none;.line2{display:none;}</style>' );
            }else { 
               echo ( '<style>.hide2{display:block;}</style>' );
            }*/


          /*if( !!empty( $sub_title_three ) ) {
               echo ( '<style>.hide3{display:none;.line3{display:none;}</style>' );
            } else { 
               echo ( '<style>.hide3{display:block;}</style>' );
            }*/

$output = "<div style='color:{$color};' data-item_title='${item_title_one}' class='item_title'><i class='fa fa-bookmark'></i> {$item_title_one}</div>
            <div class='item_container'>
              <span class='item_desc'>{$content}</span>
              <div class='line'></div>
              <div class='sub1'>{$sub_title_one}</div>
              <div class='price1'>{$currency_choice_one}{$portion_price_one} {$portion_choice_one}</div>
              <div class='between'></div>

              <div class='line2'></div>
              <div class='sub2'>{$sub_title_two}</div>
              <div class='price2'>{$currency_choice_two}{$portion_price_two} {$portion_choice_two}</div>
              <div class='between2'></div>           

              <div class='line3 hide3'></div>
              <div class='sub3 hide3'>{$sub_title_three}</div>
              <div class='price3 hide3'>{$currency_choice_three}{$portion_price_three} {$portion_choice_three}</div>
              <div class='end'></div>
            </div>";

            return $output;

          }

Open in new window


---------------------------

This is the array set for (section three)

              array(   /* sub title 3 */
                  "type" => "textfield",
                  "size" => 14,
                  "holder" => "div",
                  "class" => "",
                  "heading" => __("Name or size of portion", 'rbm_menu_item'),
                  "param_name" => "sub_title_three",
                  "value" => __("Portion not entered", 'rbm_menu_item'),
                  "description" => __("Add a menu portion name, and variables.<br>", 'rbm_menu_item')
              ),

              array(    /* currency choice 3 */
                  'type' => 'dropdown',
                  "holder" => "div",
                  "class" => "",
                  'heading' => "Currency range for portion",
                  'param_name' => 'currency_choice_three',
                  'value' => array( "", "$", "ยข" ),
                  'description' => __( " Dollars or Cents", "rbm_menu_item" )
              ),

             array(  /* portion pricing 3 */
                  "type" => "textfield",
                  "holder" => "div",
                  "class" => "",
                  "heading" => __("Price of portion", 'rbm_menu_item'),
                  "param_name" => "portion_price_three",
                  "value" => __("Price not applied", 'rbm_menu_item'),
                  "description" => __("Portion price", 'rbm_menu_item')
              ),

              array(   /* drop menu 3b */
                    'type' => 'dropdown',
                    "holder" => "div",
                    "class" => "",
                    'heading' => "Portion type or size",
                    'param_name' => 'portion_choice_three',
                    'value' => array( "", "Ea", "Pc", "Slice", "Cup", "Serving", "Limited Time", "Free" ),
                    'description' => __( "Portion type or size<br /><br /><div align='center'>***********     <img src='../wp-content/plugins/robab_menu_item/assets/thechef.png' border='0'>     ***********</div><br />", 'rbm_menu_item')
                  ),

Open in new window

---------------------------

Is there a way to  (programmatically)  accomplish this? - or some other methodology? - I'm as far as my limited knowledge goes (I am a learner in progress)
0
Daryl Isaacs
Asked:
Daryl Isaacs
  • 23
  • 8
  • 5
  • +1
1 Solution
 
MontoyaProcess Improvement MgrCommented:
 <script>
            $(document).ready(function(){
                

                $('div').filter(function() {
        return $.trim($(this).text()) === ''
}).hide();
                     });
       
        
        
        </script>

Open in new window

0
 
Daryl IsaacsAuthor Commented:
Is this a jquery remedy?

even so... it has no effect on the result
0
 
Julian HansenCommented:
Outputing style code like that - not a good idea.

Three options I can think of
1. You put the if around the actual output of the <div> - if the content of the div is empty simply don't output the div

2. You put the if around the target value for the div - if empty you give the div a class name which in your style sheet hides the div

3. You use a JavaScript solution to hide empty div's after the fact.

I would attempt the solutions in the order specified above.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Daryl IsaacsAuthor Commented:
Hi Julian,

at first glance, something comes to mind -
1)
I had tried putting some php in the $output html (I'm assuming you are talking about there) and it promptly broke WP - doesnt like it for some reason. *but... I could have coded it wrong

2)
dont know how to do that

3)
tried some jquery tests like this:
  1. $(".sub2").find('div.section:empty').hide();
  2. $(".sub3").find('div.section:empty').hide();

but they didnt get me anywhere - same with these:

/*

$(".sub2").find('div.section:empty').hide();
$(".sub3").find('div.section:empty').hide();


$(".price2").find('div.section:empty').hide();


*/

/*
function hide_empties() {
var box = document.getElementsByClassName("hide2","hide3");
var inside = document.getElementsByClassName("hide2","hide3");
if(inside.innerHTML.length > 1)    {
        box.style.display = "none";
    }    else    {
        box.style.display = "block";
    }
}

document.onload = function() {
            hide_empties();
}
*/

/*
window.onload=function(){
  if (document.getElementByClassName('sub2').childNodes.length){
      document.getElementByClassName('hide2').style.display = 'block';
   }
}


if ($("sub_title_three").html() == ""){
  $("#hide3").hide()
}
*/

But if you have a sample of something that may be usable - I would love to try it out..... :)
0
 
Julian HansenCommented:
Start with 1 - what did you try there?

I was thinking along the lines of option 1
// NB YOU HAD AN ERROR IN THE FIRST LINE OF YOUR CODE
// NOTE THE ${item instead of {$item ...
// <div style='color:{$color};' data-item_title='${item_title_one}'
//
// CONSIDER USING HEREDOC NOTATION - MUCH EASIER
$portion_price_two_output = empty($portion_price_two) ? '' : <div class="price2">{$currency_choice_two}{$portion_price_two} {$portion_choice_two}</div>";
$output = <<< OUTPUT
  <div style="color:{$color};" data-item_title="{$item_title_one}" class="item_title">
    <i class="fa fa-bookmark"></i> {$item_title_one}
  </div>
  <div class="item_container">
    <span class="item_desc">{$content}</span>
    <div class="line"></div>
    <div class="sub1">{$sub_title_one}</div>
    <div class="price1">{$currency_choice_one}{$portion_price_one} {$portion_choice_one}</div>
    <div class="between"></div>
OUTPUT;

if (!empty($portion_price_2)) {
$output .= <<< OUTPUT2
    <div class="line2"></div>
    <div class="sub2">{$sub_title_two}</div>
    <div class="price2">{$currency_choice_two}{$portion_price_two} {$portion_choice_two}</div>
OUTPUT2;

$output .= '<div class="between2"></div>';

if (!empty($sub_title_3)) {
$output <<< OUTPUT3
    <div class="line3 hide3"></div>
    <div class="sub3 hide3">{$sub_title_three}</div>
    <div class="price3 hide3">{$currency_choice_three}{$portion_price_three} {$portion_choice_three}</div>
OUTPUT2;

$output .= <<< OUTPUT_FINAL
    <div class="end"></div>
  </div>
OUTPUT_FINAL;

Open in new window

Notes:
* There is an error on the first line - not critical but will result in incorrect output.
* I am using HEREDOC notation - it is much easier to use when formatting large chunks of text for output.
* In your code you are using !!empty - which is the equivalent of empty on its own - !! cancels itself out.
* The code above conditionally adds to the output based on the state of the two variables.

This code is not tested - I am working off what you posted with no way to test - you need to look at what I have posted here and adapts to your requirements - I cannot guarantee that I have split the output in accordance with your requirements. Use the example as a guide rather than a cut and paste solution.

If you get errors - post the code and errors here.
0
 
Daryl IsaacsAuthor Commented:
Nice catch on the item title

Yep the two exclamations are from a previous iteration and I forgot to remove them - they are commented out

This type of code markup is new to me (as I said im a learner and learning as I go) - so how to implement that as a test *I :( dont know how - makes me feel soooo stooopid.

I have sent you a PM
0
 
Ray PaseurCommented:
This may or may not matter, but the use of /* ... */ makes everything inside the slash-asterisk (ie, the "..." in this statement) into a comment.  In other words, none of these PHP statements will get executed, and there will not be anything injected into the browser output stream.
          /* if( !!empty( $portion_price_two ) ) {
               echo ( '<style>.sub2{display:none;.price2{display:none;.line2{display:none;}</style>' );
            }else { 
               echo ( '<style>.hide2{display:block;}</style>' );
            }*/

Open in new window

0
 
Daryl IsaacsAuthor Commented:
Hey Ray,

thanks for the input - yes you are correct - however, I  left them in there (commented out) in case I needed to go back for whatever reason.

Too lazy to back and open previous pages *had an unfortunate occurrance where I removed a chunk of code from a different program I was  constructing, thinking I had it in the prevoius iteration, and lost it all - so now I keep bits N' pieces in commented out fashion.

I intend to remove all unwanted chunks of code from the final version though.
0
 
Julian HansenCommented:
The code is not too complicated if you get into it.

The <<< is known as HEREDOC - it is an alternative to the single / double quoted strings and has a number of advantages

1. You can use both single and double quotes in the string
2. You can embed variables in the string (as with double)
3. You can do pure text output between the opening <<< TAG and closing TAG;

The TAG is anything you want example
$myname = "Jim Bozo";
echo <<< MYTAGNAME
<h2>My name is {$myname}</h2>
MYTAGNAME;

Open in new window

you can use the <<< TAGNAME to the right of an output (echo) or assignment (=).
The closing tag must not have any characters preceding or following it - just a ; followed by a newline

That's all there is to HEREDOC - which is primarily what I have used.

As for the conditional statements

The condition statements are exactly what you had before except they now wrap the actual output of the <div>'s they pertain to - if empty no output.

Regarding the PM - feel free to upload the source file here using the attach file. I still won't be able to test it.
0
 
Daryl IsaacsAuthor Commented:
Well this is interesting - followed your suggestion and with the css set to:

.hide2, .hide3 {
    display:none;
}

with this on, this hides the field, the line prices and beginning icon (BUT) all the time and
shows text like this:
 OUTPUT; if (!empty()) { .= <<< OUTPUT2 OUTPUT2; .= ''; if (!empty()) { <<< OUTPUT3 OUTPUT3; .= <<< OUTPUT_FINAL
OUTPUT_FINAL;

now if I turn the (hide) css off

.hhide2, .hhide3 {
    display:none;
}

it shows the div contents (all of them) and the text as well - curiouser and curiouser
shot.png
0
 
Daryl IsaacsAuthor Commented:
Been asked to attach the php file - here it is

Have reverted it back to the original - but also have the heredoc one as well
robab_menu_item.phprobab_menu_item.php
robab_menu_item-heredoc.php
0
 
Julian HansenCommented:
Here is the corrected file. There were a few typos in it that I fixed.

What I cannot determine if correct is the conditional statements. In your original code you did your first check on $portion_price_two and the second on $sub_title_three - not sure why there was not consistency in the choosing of those variables however - I have kept it the same - feel free to change those as required.

I tested the file for errors and copied the $output bits to a stub and tested those with dummy data - seems to work.
robab_menu_item.php
0
 
Daryl IsaacsAuthor Commented:
Yo!..........

cookin" with gas now!

check the pic, its working as desired, what I have to add now is further color assignment capability sich as background borders etc, etc. I already have the title color change in effect, so i will duplicate that procedure to the other elements.

Also, have some serious reading on heredoc to do -- many, many thanks to you on my behalf - so much appreciated....
shot2.png
0
 
Ray PaseurCommented:
had an unfortunate occurrance where I removed a chunk of code from a different program I was  constructing, thinking I had it in the prevoius iteration, and lost it all - so now I keep bits N' pieces in commented out fashion.
Here's the link you need:
https://help.github.com/articles/good-resources-for-learning-git-and-github/
0
 
Daryl IsaacsAuthor Commented:
Thanks Ray,

have often thought about using this - scared to I guess - don't know how to work in the environment and don't want to make a total ass of myself in the process  :)

Most people I talk to use it, and are amazed that I don't - now that I've managed to cobble together a working plugin for VC, it's time I should. I have others strictly for WP, but they have been custom thingy's for clients, nothing for public consumption.

I suppose its a good a time as ever to get into git.
0
 
Daryl IsaacsAuthor Commented:
Oh before I forget - I would like to keep a relationship going with people here - how do I go about that? Is there someplace where you can add associates - like you do in LinkedIn?
0
 
Julian HansenCommented:
@Daryl,
Just checking you have everything you need?
0
 
Daryl IsaacsAuthor Commented:
Hello Julian,
Bewen getting the styling setup and adding color pickers for the text titles and areas.

I do have three background css selectors
/* price background colors */
.price1 {background-color: #e7e8c6;}
.price2 {background-color: #d4ebf0;}
.price3 {background-color: #e7dd95;}

these control the colored areas behind the $ sign, the price and the selections configuration.

Im trying to get the picker in the admin area la sample of the picker you can find in the php I sent (all Im doing is copying that block, renaming it and putting it in the proper area of the array to affect whatever text area I want) All that is well and good, and working fine.

Now Im trying to get the same picker to point at the css and change the background usingt php in the css like this
/* price background colors */
.price1 {background-color: <?php echo('price_one_bgd'); ?>}
.price2 {background-color: <?php echo('price_two_bgd'); ?>}
.price3 {background-color: <?php echo('price_three_bgd'); ?>}

and so on through all the three selectors

then I'm on to getting a small chili pepper icon to show when a checkbox is clicked for "hot"

This is coming along fabulous otherwise - I have a couple of things like that left and its finito - cool

regards
Daryl
0
 
Ray PaseurCommented:
Is there someplace where you can add associates - like you do in LinkedIn?
This might exist at E-E, but it's not really been clearly communicated (at least not to me).  There is a "follow" thing.  Mostly I just use LinkedIn.

Also, Git is your friend.  It's really very easy to use.  This is the model I follow.
http://nvie.com/posts/a-successful-git-branching-model/

Basically: Make a branch from develop, try something, run my tests. decide if I like the work.  If so, merge it back into the develop branch.  If not, shit-can it.  A naming convention that associates the Git branches with the Agile stories (or tasks or whatever you call them) is really useful.
0
 
Julian HansenCommented:
Just a note on style - these should be set in your style sheet - you should use code simply to add classes that are linked to styles in your style sheet.
0
 
Daryl IsaacsAuthor Commented:
Yes.. agree... pulled a swifty doing that (and used your excellent heredoc procedure.

Created a new text array above the main title and added a cllass to it - I then added it to the html output using the heredoc way of doing that - (took a little figuring, but I got it)

SO, now in the plugin back end there is another little controller that allows the user to type in a numerical amount - the result is a little red number that shows (only if the field is populated)  AND has a little pepper icon beside it (adding the cutesy factor to that)

It tells the user if the item is hot or not and how spicy it is.

As far as controlling the css via php - know about it - never had the need to try it til now - so this also is a work in progress ( heh - like me)

did you get my linkedin invite?
0
 
Daryl IsaacsAuthor Commented:
On a side note - you know all this little stuff I'm learning about php, css, sass, etc, etc. is not taught anywhere, by anyone.

Sure there are tutorial places all ove, but they all just simply cover the basics in one way or another - in-depth or fundamentally intelligent ways of creating results from procedures are only learnt the hard way I guess.

If someone with the wherewithall and the technical skills could probably make a pretty penny by going further then the basics - take me for example. I know enough to make myself dangerous BUT am real thirsty AND willing to learn (I'll bet there are a lot of people out there just like me [face it if there were'nt, places like the EE would not even exist] right?

So, with all that said, I again thank you for your help -  :)
0
 
Daryl IsaacsAuthor Commented:
here you go - only shows if theres data in the field - coolness!
Screen-Shot-2016-08-23-at-11.47.30-P.png
0
 
Ray PaseurCommented:
could probably make a pretty penny by going further then the basics
Maybe so.  A college degree in computer science will teach the basics as well as the current technological implementations.  I'm not exaggerating when I say it can take years of dedicated study to become proficient.  And technology fields like mobile and web development are constantly advancing, so it's a life-long learning process.
0
 
Daryl IsaacsAuthor Commented:
To keep all updated - been editing the backend of the system for a user to navigate through the controls easier - same kind of interface look and feel as the front end.

Trying to make sure this is really easy for a user to comprehend and utilize.

Finding that possibly checkboxes and/or radios may be an annswer to spacing problems. Will keep updated.

CHEERS :)
0
 
Daryl IsaacsAuthor Commented:
Adding to above - I managed to get a row of checkboxes and their labels to display in the editor area, however the output from that is simply #999999 - something with the way the html return is configured I guess.

BUT... its pretty ungainly and cumbersome, so here is where the radios come in! Click on one for the choice - and a radio set will only allow one choice - and depending on the choice, the appropriate graphic will display. Fir the first /default choice it will be a transparent png file so it will show nothing.

The radios do not display at all along with their respective labels - tried 'type' => 'radio', and 'type' => 'radiogroup', but nothing - egad, I'm at least used to seeing them - even if they dont work.....

As I mentioned earlier, I'm using a text field to display a number range for the little "pepper" icon - if not filled in does not show - the text box div contains the image.

I was going to use this trick for a series of "Chef's Special", "This week only",  "til supplies last" that type of thing - and have a colored triangle cover the upper right corner of the display box with the text on that.

I could also use it for some other fancy things like switching the stylesheet to show different types of borders etc - possibly a case switch of some kind. (that could be applied to checkbox also I assume.

The reason I'm doing all these different situations, is .... I've spoken to a few restaurant owners and they all ask for similar ( with variations ) so, the best thing for me is to do them all now and get it all done so's I don't have to redo all this again in another rev. ( It's way easier to turn stuff off, than to turn it on - especially later on down the line - I'm sure you "geeky" readers know what I'm getting at ) hence the reason I comment everything and/or keep it laying around - never know when I have to go back and "revisit" some earlier code ( sic )

I am going to "fiddle" with getting some form of passable reslts from the boxes and radios.

Again, will keep you'all posted.
0
 
Ray PaseurCommented:
Sounds like this might be the perfect exercise for E-E Gigs.  You can get hands-on help from an expert!
0
 
Daryl IsaacsAuthor Commented:
Already did that with both Ray and Julian ( and now you ) heh-heh
0
 
Daryl IsaacsAuthor Commented:
My head is getting ready to explode

tried so many variant to get the checkboxes to (kinda) work - they show the data -but if not checked I get #99999
tried these
//if (!($checkbox_test).length>0) 
        //if(!empty($checkbox_test)) 
        //if(!empty(['checkbox_test'])) 
        //if(!empty($checkbox_test).length>0)
        //if(!empty($checkbox_test->value))
        if(!empty($checkbox_test).length) {

Open in new window


commented each one out before I try the next - no go pards

attaching the revised/upgraded version
robab_menu_item.php
0
 
Daryl IsaacsAuthor Commented:
Same with radios - I like the way they cut down on footprint space - but they are b*****s to work with
0
 
Daryl IsaacsAuthor Commented:
Got it - had to add some initial attributes for the checkboxes (which I inadvertantly set to a color variable)

/////// this is a test of these two
                    'checkbox_test' => '',
                    'radio_test' => '',
                    ///////

Open in new window


now because the values AND the labels are in one array with ONE id

'value' => array( 'Eggs'=>' Eggs ', 'Cheese'=>' Cheese ', 'Toast'=>' Toast ' ),

Open in new window


I have to figure how to split them so I can apply different results to each based on the user clicks/preferences.  [Radios, also]
0
 
Daryl IsaacsAuthor Commented:
A thought comes to mind --

what about this:

putting this into the heredoc after its function call

  if ( ($checkbox_test) == "Cheese" ){
               echo "<div class="cheesediv"></div>";
        }

Open in new window


that way it could check whats in the checkbox test and if it matches (any) of the array items it would display the appropriate div

I can only assume it would require some thing like
$checkbox_test = "$checkbox_test";

Open in new window

to start with... I put $checkbox_test in the second part as I didnt know how to code it correctly - Im batting wildly here.

This could read whatever the result (from the array and if it matches then it will do the div thing - and a different div class for each of the array variables - make sense? heh it does to me :)
0
 
Julian HansenCommented:
@Daryl,
This discussion looks like it is deviating from the original question - which I am assuming has been solved?

If you are still having issues around the original question can you post details of exactly what you are needing - if not you should close this question and open another one with your new issue - that way you will get the most exposure.

If you do open another question then you can reference this one so that any new experts who pick up the second question can get up to speed with what the issue is.
2
 
Daryl IsaacsAuthor Commented:
OK I can do that - the only reason I stayed here is because its an ongoing thing for me - but if it requires sectioning I can do that - sorry :(
0
 
Daryl IsaacsAuthor Commented:
Very helpful
0
 
Daryl IsaacsAuthor Commented:
I do not believe that I am being a troll... I have been very respectful to anyone I have spoken to here as well as been very appreciative of the help I have received.

A troll by definition is someone who sows discord and argument for the sake of arguing and being disruptive - in the few messages I have made here NONE of them have been inflammatory or condescending, argumentative or disrespectful.

I feel that the person stating that I am a troll is in error. I f anyone care to read through the single posting I have here will concur that I have treated everyone with the highest regard.
0
 
Julian HansenCommented:
@Daryl,

To get the most out of the service it is best to keep interactions short - that way you can stay engaged with the experts and get good responses, for us to have multiple questions open for long periods of time - it is difficult to keep engaged.

Please feel free to continue seeking assistance either through questions, gigs or live - there is nothing wrong with asking questions. The problem with long threads is that the longer they are the less likely you are going to get a response as they start heading off into TLDR territory.
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

  • 23
  • 8
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now