INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

jQuery hide div class if total equal to 0

jQuery hide div class if total equal to 0

(OP)
Hi!

I'm struggling for a few days to solve a problem. I have a floating cart plugin from MarketPress, it's a free plugin, I want to make it hide when it's empty but it doesn't work.
I've added an if statement where the code is underlined but it doesn't work. Can you help me please?
Cheers,
Nelutu

here is the code

CODE --> Javascript

<!-- Load JS -->
				<script type="text/javascript">
				
				jQuery(document).ready(function () {
					
					// floating cart		
					jQuery(document).ajaxComplete(function(e, xhr, settings) {
						var tot = 0;
						var cart_tot = 0;
                        
						
						<?php if ( $showcartitem == 'yes' ) { ?> 	
							jQuery.each(jQuery('#cart-section td.mp_cart_col_quant'),function(){
								var qty = jQuery(this).html() - 0;
								if(!isNaN(qty)){
									tot += qty;
                              
								}
							});
                                    
							jQuery('.floating-cart span.cart-total-items').html(tot);
                            if (tot <=0){
                          $(".floating-cart").hide();                   
                                    }
						<?php } ?>

						<?php if ( $showcartamount == 'yes' ) { ?> 	

							jQuery.each(jQuery('#cart-section td.mp_cart_col_total'),function(){
								cart_tot = jQuery(this).html();
							});

							jQuery('.floating-cart span.cart-total-amount').html(cart_tot);

						<?php } ?>

					});

				});

				</script>

				<?php

			}

		}

		function floating_cart_contents_in_button( $echo = true , $settings = '' ){

			$showbtntext = esc_attr($settings['fcsettings_general_show_button_text']);
			$buttontext = esc_attr($settings['fcsettings_general_button_text']);
			$showcartitem = esc_attr($settings['fcsettings_general_show_cart_total_item']);
			$showcartamount = esc_attr($settings['fcsettings_general_show_cart_total_amount']);

			$output = '';

			if ( $showcartitem == 'yes' )
				$output .= '<span class="cart-total-items">'.mp_items_count_in_cart().'</span>'.__( ' item(s)' , 'floating-cart' );

			if ( $showcartitem == 'yes' && $showcartamount ==  'yes'  )
				$output .= ' - ';

			if ( $showcartamount ==  'yes' )
				$output .= '<span class="cart-total-amount">'.$this->floating_cart_total_amount_in_cart( false ).'</span>';
			
			if ( $showbtntext == 'yes' )
				$output .= '<span class="view-cart"> - '.__( $buttontext, 'floating-cart' ).'</span>';

			if ($echo) {
			    echo $output;
			} else {
			    return $output;
			}
		}

		function floating_cart_total_amount_in_cart( $echo = true ) {

		  	global $mp, $blog_id;
		  	$blog_id = (is_multisite()) ? $blog_id : 1;
		  	$current_blog_id = $blog_id;

			$global_cart = $mp->get_cart_contents(true);
		  	if (!$mp->global_cart)  //get subset if needed
		  		$selected_cart[$blog_id] = $global_cart[$blog_id];
		  	else
		    	$selected_cart = $global_cart;

		    $totals = array();

		    if ( !empty($selected_cart)) {

			    foreach ($selected_cart as $bid => $cart) {

					if (is_multisite())
				        switch_to_blog($bid);

				    if (!empty($cart)) {
					   	foreach ($cart as $product_id => $variations) {
					        foreach ($variations as $variation => $data) {
					          $totals[] = $data['price'] * $data['quantity'];
					        }
					      }
				    }

			    }
		    }
		    
			if (is_multisite())
		      switch_to_blog($current_blog_id);

		    $total = array_sum($totals);

			if ($echo) {
			    echo $mp->format_currency('', $total);
			} else {
			    return $mp->format_currency('', $total);
			}
		}

		function floating_cart_plugin_updater_init() {

			include_once( $this->plugin_path .'inc/fc-updater.php' );

			if ( ! defined( 'WP_GITHUB_FORCE_UPDATE' ) ) {
				define( 'WP_GITHUB_FORCE_UPDATE', true );
			}

			if ( is_admin() ) {

				$config = array(
					'slug' => plugin_basename( __FILE__ ),
					'proper_folder_name' => 'mp-floating-cart',
					'api_url' => 'https://api.github.com/repos/nathanonn/mp-floating-cart',
					'raw_url' => 'https://raw.github.com/nathanonn/mp-floating-cart/master',
					'github_url' => 'https://github.com/nathanonn/mp-floating-cart',
					'zip_url' => 'https://github.com/nathanonn/mp-floating-cart/zipball/master',
					'sslverify' => true,
					'requires' => '3.5',
					'tested' => '3.5.1',
					'readme' => 'README.md',
					'access_token' => '',
				);

				new WP_GitHub_Updater( $config );

			}
		}

	}

	new MPFloatingCart();

?> 

RE: jQuery hide div class if total equal to 0

(OP)
Sorry guys,

Here is the code underlined where I added an if statement

Cheers

CODE --> Javascript

<!-- Load JS -->
				<script type="text/javascript">
				
				jQuery(document).ready(function () {
					
					// floating cart		
					jQuery(document).ajaxComplete(function(e, xhr, settings) {
						var tot = 0;
						var cart_tot = 0;
                        
						
						<?php if ( $showcartitem == 'yes' ) { ?> 	
							jQuery.each(jQuery('#cart-section td.mp_cart_col_quant'),function(){
								var qty = jQuery(this).html() - 0;
								if(!isNaN(qty)){
									tot += qty;
                              
								}
							});
                                    
							jQuery('.floating-cart span.cart-total-items').html(tot);
                            if (tot <=0){
                          jQuery(".floating-cart").hide();                   
                                    }
						<?php } ?>

						<?php if ( $showcartamount == 'yes' ) { ?> 	

							jQuery.each(jQuery('#cart-section td.mp_cart_col_total'),function(){
								cart_tot = jQuery(this).html();
							});

							jQuery('.floating-cart span.cart-total-amount').html(cart_tot);

						<?php } ?>

					});

				});

				</script>

				<?php

			}

		}

		function floating_cart_contents_in_button( $echo = true , $settings = '' ){

			$showbtntext = esc_attr($settings['fcsettings_general_show_button_text']);
			$buttontext = esc_attr($settings['fcsettings_general_button_text']);
			$showcartitem = esc_attr($settings['fcsettings_general_show_cart_total_item']);
			$showcartamount = esc_attr($settings['fcsettings_general_show_cart_total_amount']);

			$output = '';

			if ( $showcartitem == 'yes' )
				$output .= '<span class="cart-total-items">'.mp_items_count_in_cart().'</span>'.__( ' item(s)' , 'floating-cart' );

			if ( $showcartitem == 'yes' && $showcartamount ==  'yes'  )
				$output .= ' - ';

			if ( $showcartamount ==  'yes' )
				$output .= '<span class="cart-total-amount">'.$this->floating_cart_total_amount_in_cart( false ).'</span>';
			
			if ( $showbtntext == 'yes' )
				$output .= '<span class="view-cart"> - '.__( $buttontext, 'floating-cart' ).'</span>';

			if ($echo) {
			    echo $output;
			} else {
			    return $output;
			}
		}

		function floating_cart_total_amount_in_cart( $echo = true ) {

		  	global $mp, $blog_id;
		  	$blog_id = (is_multisite()) ? $blog_id : 1;
		  	$current_blog_id = $blog_id;

			$global_cart = $mp->get_cart_contents(true);
		  	if (!$mp->global_cart)  //get subset if needed
		  		$selected_cart[$blog_id] = $global_cart[$blog_id];
		  	else
		    	$selected_cart = $global_cart;

		    $totals = array();

		    if ( !empty($selected_cart)) {

			    foreach ($selected_cart as $bid => $cart) {

					if (is_multisite())
				        switch_to_blog($bid);

				    if (!empty($cart)) {
					   	foreach ($cart as $product_id => $variations) {
					        foreach ($variations as $variation => $data) {
					          $totals[] = $data['price'] * $data['quantity'];
					        }
					      }
				    }

			    }
		    }
		    
			if (is_multisite())
		      switch_to_blog($current_blog_id);

		    $total = array_sum($totals);

			if ($echo) {
			    echo $mp->format_currency('', $total);
			} else {
			    return $mp->format_currency('', $total);
			}
		}

		function floating_cart_plugin_updater_init() {

			include_once( $this->plugin_path .'inc/fc-updater.php' );

			if ( ! defined( 'WP_GITHUB_FORCE_UPDATE' ) ) {
				define( 'WP_GITHUB_FORCE_UPDATE', true );
			}

			if ( is_admin() ) {

				$config = array(
					'slug' => plugin_basename( __FILE__ ),
					'proper_folder_name' => 'mp-floating-cart',
					'api_url' => 'https://api.github.com/repos/nathanonn/mp-floating-cart',
					'raw_url' => 'https://raw.github.com/nathanonn/mp-floating-cart/master',
					'github_url' => 'https://github.com/nathanonn/mp-floating-cart',
					'zip_url' => 'https://github.com/nathanonn/mp-floating-cart/zipball/master',
					'sslverify' => true,
					'requires' => '3.5',
					'tested' => '3.5.1',
					'readme' => 'README.md',
					'access_token' => '',
				);

				new WP_GitHub_Updater( $config );

			}
		}

	}

	new MPFloatingCart();

?> 

RE: jQuery hide div class if total equal to 0

(OP)
I don't get anything...

RE: jQuery hide div class if total equal to 0

Then there isn't an ajax request being triggered to fire your '.ajaxComplete' function.

Does this only get fired when an item is added or removed from the cart or does it never fire?

Do you have any errors in the error console (F12)?

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: jQuery hide div class if total equal to 0

i'm not sure about using a jquery collection inside $.each. that's not what it's there for.

use this instead

CODE

jQuery('#cart-section td.mp_cart_col_quant').each(function(){
 var qty = jQuery(this).html() - 0;
 if(!isNaN(qty)) tot += qty;
}); 

rather than rely on the first line of the anonymous function, i think it would be better to _know_ what the possible states of the html are. and perhaps also use text() rather than html() so that you're not picking up any inline formatting.

RE: jQuery hide div class if total equal to 0

(OP)
Hi
@1DMF
This are the errors that i get


This are the errors that I get when I add an item


@jpadie
I've tried to use your code and also i've used text() instead of html() but nothing.

RE: jQuery hide div class if total equal to 0

ditto the store.js file. both being loaded from the same location.

RE: jQuery hide div class if total equal to 0

(OP)
I've followed the address from the error and the files weren't there, so i've looked for them and they were in another folder, i've copied them where they were requested, the errors dissappeared, the attention signs are still there. Cart doesn't seem to dissappear.
I can't figure it. pc1

RE: jQuery hide div class if total equal to 0

(OP)
This is how Inspection board looks now.

RE: jQuery hide div class if total equal to 0

don't worry about the warning signs. they are warnings, not errors.

is showcart set to yes such that the javascript is actually being output to the page

CODE

//to debug
<?php $showcartitem = $showcartamount = 'yes'; ?>
<?php if ( $showcartitem == 'yes' ) { ?> 	
	jQuery('#cart-section td.mp_cart_col_quant').each(
		function(){
			var qty = jQuery(this).text() - 0;
			if(!isNaN(qty)) tot += qty;                  
		}
	);
	                                    
	jQuery('.floating-cart span.cart-total-items').html(tot);
	if (tot <=0){
		jQuery(".floating-cart").hide();                   
	} else {
		jQuery(".floating-cart").show();
	}
<?php } ?>
<?php if ( $showcartamount == 'yes' ) { ?> 	
	var cart_tot = jQuery('#cart-section td.mp_cart_col_total').html();
	jQuery('.floating-cart span.cart-total-amount').html(cart_tot);	
<?php } ?> 

RE: jQuery hide div class if total equal to 0

Does that alert fire now the script is loading?

You need to figure out when the ajax request is triggered and therefore the ajaxComplete();

If no ajax request is triggered when the page first loads, you could simply put it at the tail end of the document.ready function.

I'm assuming the ajax request is only for when items are added to the cart or removed, so you need the one testing for zero in the ajaxComplete() and an initial one at the end of the document.ready...

CODE

jQuery(document).ready(function () {

   ... all the code you have...

   $(".floating-cart").hide();
}); 
or you could simply have an initial state via the css

CODE

.floating-cart {
    display:none;
} 
But you need something to ensure this is toggled when an item is added.

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: jQuery hide div class if total equal to 0

(OP)
@jpadie
showcart is set to yes now.:)
@1DMF
the alert is firing, the ajax is requested i've added

CODE --> Javascript

$(".floating-cart").hide(); 
and the cart it's hidden now. :)

RE: jQuery hide div class if total equal to 0

so all is now working?

RE: jQuery hide div class if total equal to 0

(OP)
now it's hidden even when if the value is bigger than 0. when I reload the page it shows up for a brief second.

RE: jQuery hide div class if total equal to 0

i see.

this would be easier to help you debug if you could post the code to an external site. or post the entirety of the rendered source code.

RE: jQuery hide div class if total equal to 0

(OP)
I run the site on localhost. If you want i can give you my TeamViewer ID. If you are ok with that.

RE: jQuery hide div class if total equal to 0

I would have thought what jpadie posted would have resolved the problem

CODE

if (tot <=0){
		jQuery(".floating-cart").hide();                   
	} else {
		jQuery(".floating-cart").show();
	} 

how are you checking the values of tot to ensure it is greater than 0?
you could just before that if statement debug to console

CODE

console.log('tot='+tot); 

and confirm its value.

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: jQuery hide div class if total equal to 0

(OP)
Hello,

Sorry for not responding, i don't know how to check if the values are greater than 0.

CODE -->

console.log('tot='+tot); 
it doesn't show anything in the inspection console.

RE: jQuery hide div class if total equal to 0

I take it you put that below this line

CODE

jQuery('.floating-cart span.cart-total-items').html(tot); 
if so and nothing is output to the console I can only assume

CODE

<?php if ( $showcartitem == 'yes' ) { ?> 
is evaluating to false?

"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: jQuery hide div class if total equal to 0

(OP)
so what can be done if that's the case. :)

RE: jQuery hide div class if total equal to 0

@bluemask11

you need to help yourself a bit. or at least help us to help you.

either this is a php question (related to incorrect parsing/setting of $showcartitem) or it is a javascript question.

if it is a php question you need to provide your php code and the mechanisms for setting those variables so we can help.

if it is a javascript question you need to provide either a link to the site (and if you are developing on a localhost then buy a cheap vps such as those at digitalocean and upload the files to that. For 5$ a month it won't break the bank ... OR post the entire RENDERED code here so that we can duplicate the environment and work out what is going wrong.

If $showcartitem is evaluating to false then simply set it to true at least for debugging. then you can narrow down the issue to one line of enquiry or the other.

RE: jQuery hide div class if total equal to 0

(OP)
Hi guys,

I solved the problems, I used another plugin. Thank you for your cooperation. When it will be finished i`ll invite you to see it.
Have a nice day.
:);)

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close