Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

jQuery hide div class if total equal to 0

Status
Not open for further replies.

bluemask11

Programmer
Feb 25, 2015
12
RO
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
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' => '[URL unfurl="true"]https://api.github.com/repos/nathanonn/mp-floating-cart',[/URL]
					'raw_url' => '[URL unfurl="true"]https://raw.github.com/nathanonn/mp-floating-cart/master',[/URL]
					'github_url' => '[URL unfurl="true"]https://github.com/nathanonn/mp-floating-cart',[/URL]
					'zip_url' => '[URL unfurl="true"]https://github.com/nathanonn/mp-floating-cart/zipball/master',[/URL]
					'sslverify' => true,
					'requires' => '3.5',
					'tested' => '3.5.1',
					'readme' => 'README.md',
					'access_token' => '',
				);

				new WP_GitHub_Updater( $config );

			}
		}

	}

	new MPFloatingCart();

?>
 
Sorry guys,

Here is the code underlined where I added an if statement

Cheers

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);
                          [u]  if (tot <=0){
                          jQuery(".floating-cart").hide();                   
                                    }[/u]
						<?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' => '[URL unfurl="true"]https://api.github.com/repos/nathanonn/mp-floating-cart',[/URL]
					'raw_url' => '[URL unfurl="true"]https://raw.github.com/nathanonn/mp-floating-cart/master',[/URL]
					'github_url' => '[URL unfurl="true"]https://github.com/nathanonn/mp-floating-cart',[/URL]
					'zip_url' => '[URL unfurl="true"]https://github.com/nathanonn/mp-floating-cart/zipball/master',[/URL]
					'sslverify' => true,
					'requires' => '3.5',
					'tested' => '3.5.1',
					'readme' => 'README.md',
					'access_token' => '',
				);

				new WP_GitHub_Updater( $config );

			}
		}

	}

	new MPFloatingCart();

?>
 
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
 
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.
 
Hi
@1DMF
This are the errors that i get
qrkzrp.png


This are the errors that I get when I add an item
28vd74m.png


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

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

 
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]
 
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 } ?>
 
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
 
@jpadie
showcart is set to yes now.:)
@1DMF
the alert is firing, the ajax is requested i've added
JavaScript:
$(".floating-cart").hide();
and the cart it's hidden now. :)
 
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.
 
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.
 
I run the site on localhost. If you want i can give you my TeamViewer ID. If you are ok with that.
 
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
 
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.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top