Перейти к публикации
Поиск в
  • Дополнительно...
Искать результаты, содержащие...
Искать результаты в...

[Решено?..] addToCart не принимает количество


Sneyk
 Поделиться

Рекомендованные сообщения

Есть 

       <a onclick="addToCart('<?php echo $result['product_id']; ?>, 3');">Добавить в корзину</a>

И js. который добавляет товар

function addToCart(product_id, quantity) {
	var productpage = true;

	if (typeof(product_id) != 'undefined') {
		var productpage = false;
		var quantity = typeof(quantity) != 'undefined' ? quantity : 1;
		var data = 'product_id=' + product_id + '&quantity=' + quantity;
	} else {
		var quantity = $('input[name=\'quantity\']').val();
		var data =  $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea');
	}

	$('#text-added').text(quantity + ' '+declination(parseInt(quantity)));

	$.ajax({
		url: 'index.php?route=checkout/cart/add',
		type: 'post',
		data: data,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information, .error').remove();
			
			if (json['redirect'] && !productpage) {
				location = json['redirect'];
			}

			if (json['error'] && productpage) {
				if (json['error']['option']) {
					for (i in json['error']['option']) {
						$('#option-' + i).after('<span class="error">' + json['error']['option'][i] + '</span>');
					}
				}
			} 
			
			if (json['success']) {
				$('#cart-total, .cart-total').html(json['total']);
				$('#cartpopup .cart').load('index.php?route=module/cart .mini-cart-info', function() {

					$('#cartpopup .mini-cart-info td.remove img').each(function(i,e){
						var $this = $(this);
						var product_id = $this.attr('onclick').match(/remove=(\d+(?::[\w=\+\\]+)?)/)[1];
						this.onclick = function () {
							$('#cart').load('index.php?route=module/cart&remove=' + product_id + ' #cart > *', function(){$('.cart-total').text($('#cart-total').text());});
							$this.parent().parent().hide();
							if ($('#cartpopup .mini-cart-info tr').filter(':visible').length == 0) {
								$('#cartpopup').popup('hide');
							}							
						}
					});

					$('#cartpopup').popup('show');
					
				});
			}	
		}
	});
}

Но почему то js не воспринимает "quantity" и всегда добавляет по 1 товару в корзину... 

Ссылка на комментарий
Поделиться на других сайтах

  • 6 месяцев спустя...
  • 6 месяцев спустя...

Может и мне кто поможет?

Также не добавляется количество в корзину.

 

Вывод на странице:

<div class="addproduct">
            <div class="product_add">
			<a onclick="addToCart('<?php echo $product_id; ?>',this);">
			<span><img src="catalog/view/theme/Basico/image/add_icon.png" alt="add icon"/><?php echo $button_cart; ?>
			</span>
			</a>
			</div>
         			<input type="text" name="quantity" size="2" class="product_number"  value="<?php echo $minimum; ?>" />
            <input type="hidden" name="product_id" size="2" value="<?php echo $product_id; ?>" />
            <div class="qty"><?php echo $text_qty; ?></div>
          </div>
                  </div> 

 Часть common.js

 

function addToCart(product_id) {
	$.ajax({
		url: 'index.php?route=checkout/cart/update',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information, .error').remove();
			
			if (json['redirect']) {
				location = json['redirect'];
			}
			
			if (json['error']) {
				if (json['error']['warning']) {
					$('#notification').html('<div class="warning" style="display: none;">' + json['error']['warning'] + '<img src="catalog/view/theme/Basico/image/close.png" alt="" class="close" /></div>');
					
					$('.warning').fadeIn('slow');
					
					$('html, body').animate({ scrollTop: 0 }, 'slow');
				}
			}	 
			if (json['success']) {	
				html = '<div class="popup-cart-info"><div class="popup-close"><a alt="Закрыть" onclick="closeCart();" title="Закрыть" ><img src="catalog/view/javascript/jquery/fancybox/fancy_close.png"></a></div>';
				AltImg = $('a[onclick="addToCart(\'' + product_id + '\');"]').parent().parent().parent().find('.left .image a img');
				if(AltImg.length) {
					html += '<div class="cart-box-img"><img style="width:130px;" src="' + AltImg.attr('src') + '" /></div>';
				} 
				html +=	'<div class="cart-box-succ-det">' + json['success'] + '</div>';
				html +=	'<div class="cart-box-list">' + json['output']  +  '</div>';
				html +=	'<div class="popup-buttons"><div class="left"><a alt="Продолжить" onclick="closeCart();" title="Продолжить" class="button"><span>Продолжить</span></a></div><div class="right"><a href="index.php?route=checkout/simplecheckout" class="button"><span>Оформить</span></a></div></div>';
				html += '</div>';
				$('#cart-success').html('<div class="cart-conf-popup">' + html + '</div>');

				var opaclayerHeight = $(document).height();
				var opaclayerWidth = $(window).width();

				$('#opaclayer').css('height', opaclayerHeight);			

				var winH = $(window).height();
				var winW = $(window).width();

				$('.cart-conf-popup').css('top',  winH/2-$('.cart-conf-popup').height()/2);
				$('.cart-conf-popup').css('left', winW/2-$('.cart-conf-popup').width()/2);				
				$('#opaclayer').fadeTo(500,0.8);
				$('.cart-conf-popup').fadeIn(500); 					
				$('#cart_total').html(json['total']);
			}	
		}
	});
}	
function closeCart() {
	$('#opaclayer').fadeOut(500, function() {
		$('#opaclayer').hide().css('opacity','1');
	});
	$('.cart-conf-popup').fadeOut(500, function() {
		$('.cart-conf-popup').remove();
	});
	$('.popup-close').fadeOut(500, function() {
		$('.popup-close').remove();
	});

}

function removeCart(key) {
	$.ajax({
		url: 'index.php?route=checkout/cart/update',
		type: 'post',
		data: 'remove=' + key,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();
			
			if (json['output']) {
				$('#cart_total').html(json['total']);
				
				$('#cart .content').html(json['output']);

				$('#cart .cart-box-list').html(json['total']);
				$('.cart-box-list').html(json['output']);
			}			
		}
	});
}
function removeCartlocation(key) {
	$.ajax({
		url: 'index.php?route=checkout/cart/update',
		type: 'post',
		data: 'remove=' + key,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();
			
			if (json['output']) {
				$('#cart_total').html(json['total']);
				
				$('#cart .content').html(json['output']);

				$('#cart .cart-box-list').html(json['total']);
				$('.cart-box-list').html(json['output']);
				location='index.php?route=checkout/cart';
			}			
		}
	});
}

function removeVoucher(key) {
	$.ajax({
		url: 'index.php?route=checkout/cart/update',
		type: 'post',
		data: 'voucher=' + key,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();
			
			if (json['output']) {
				$('#cart_total').html(json['total']);
				
				$('#cart .content').html(json['output']);
			}			
		}
	});
} 

 

 

У меня, насколько я понимаю, вообще вырезано количество в коде js

 

Подстановка

function addToCart(product_id, quantity) {
	var productpage = true;

	if (typeof(product_id) != 'undefined') {
		var productpage = false;
		var quantity = typeof(quantity) != 'undefined' ? quantity : 1;
		var data = 'product_id=' + product_id + '&quantity=' + quantity;
	} else {
		var quantity = $('input[name=\'quantity\']').val();
		var data =  $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea');
	}

	$('#text-added').text(quantity + ' '+declination(parseInt(quantity)));

не помогла.

Ссылка на комментарий
Поделиться на других сайтах


Создайте аккаунт или войдите в него для комментирования

Вы должны быть пользователем, чтобы оставить комментарий

Создать аккаунт

Зарегистрируйтесь для получения аккаунта. Это просто!

Зарегистрировать аккаунт

Войти

Уже зарегистрированы? Войдите здесь.

Войти сейчас
 Поделиться

  • Сейчас на странице   0 пользователей

    • Нет пользователей, просматривающих эту страницу.
×
×
  • Создать...

Важная информация

На нашем сайте используются файлы cookie и происходит обработка некоторых персональных данных пользователей, чтобы улучшить пользовательский интерфейс. Чтобы узнать для чего и какие персональные данные мы обрабатываем перейдите по ссылке. Если Вы нажмете «Я даю согласие», это означает, что Вы понимаете и принимаете все условия, указанные в этом Уведомлении о Конфиденциальности.