Jump to content
Sign in to follow this  
DRONGO

Помогите наладить JS, объединить

Recommended Posts

Продавец модуля проигнорил... переделываю его сам.

 

Сначала купил модуль категории во вкладках, переверстал его под себя, добавил имеющийся у меня функционал кнопочек и поле изменения кол-ва товара, потом купил модуль вывод опций в рекомедуемых и интегрировал его в предыдущий модуль. Опции вывел, они добавлялись в корзину, но через раз (к одному товару 1 опция добавится, а потом глушняк - не добавляется)! К тому же там у меня конфликт скриптов (не совместимы классы onclick="....)

 

В общем, на данный момент у меня: не добавляется опция в корзину и не добавляется выбранное кл-во товара...  Пожалуйста, помогите решить проблему, очень нужно!

 

randprod.tpl (шаблон модуля - категории во вкладках) В нём же конфликтующие скрипты для кнопок и добавления опций.

<div id="tabs" class="htabs">
<?php foreach ($categories as $category) { ?>
<a href="#catagory<?php echo $module.$category['category_id']; ?>" class="selected"><?php echo $category['name']; ?></a>
<?php } ?>
</div>

<?php ?>

<?php foreach ($categories as $category) { 
    $products = $category['products'];
?>
<div id="catagory<?php echo $module.$category['category_id']; ?>" class="tab-content" >

<div class="box-product">
<?php foreach ($products as $product) { ?>
<div class="gutter-sizer">


<div class="image"><img src="<?php echo $product['thumb']; ?>" alt="<?php echo $product['name']; ?>" /></div>
<div class="name"><a href="<?php echo $product['href']; ?>"><?php echo $product['name']; ?></a></div>

<?php if ($product['price']) { ?>
<div class="price">
<?php if (!$product['special']) { ?>
<?php echo $product['price']; ?>
<?php } else { ?>
<span class="price-old"><?php echo $product['price']; ?></span> <span class="price-new"><?php echo $product['special']; ?></span>
<?php } ?>
</div>
<?php } ?>
<?php if ($product['rating']) { ?>
<div class="rating"><img src="catalog/view/theme/default/image/stars-<?php echo $product['rating']; ?>.png" alt="<?php echo $product['reviews']; ?>" /></div>
<?php } ?>

    
<div class="buton_container">
 

<?php if ($product['options']) { ?>
<div class="options" id="option_<?php echo $product['product_id']; ?>">
							<br />
							<?php foreach ($product['options'] as $option) { ?>
							<?php if ($option['type'] == 'select') { ?>
							<div id="option-<?php echo $option['product_option_id']; ?>" class="option">
							  <?php if ($option['required']) { ?>
							  <span class="required">*</span>
							  <?php } ?>
							  <b><?php echo $option['name']; ?>:</b><br />
							  <select name="option[<?php echo $option['product_option_id']; ?>]">
								<option value=""><?php echo $text_select; ?></option>
								<?php foreach ($option['option_value'] as $option_value) { ?>
								<option value="<?php echo $option_value['product_option_value_id']; ?>"><?php echo $option_value['name']; ?>
								<?php if ($option_value['price']) { ?>
								(<?php echo $option_value['price_prefix']; ?><?php echo $option_value['price']; ?>)
								<?php } ?>
								</option>
								<?php } ?>
							  </select>
							</div>
							<br />
							<?php } ?>
							
							<?php } ?>

						  </div>
<?php } ?>	  


<input type="button" value="-" class="minus">
<span class="buton_input"><input type="text" maxlength="3" value="1" size="4" class="item-<?php echo $product['product_id']; ?> kolvo" /></span>
<input type="button" value="+" class="plus">


<div class="cart">
<input type="button" value="добавить к заказу" onclick="add_bc('<?php echo $product['product_id']; ?>');" class="button" />
</div>

</div>
</div>
<?php } ?>
</div></div>


<?php } ?>
<script type="text/javascript">
				function add_bc(product_id) {
					data = $('#option_'+product_id+' input[type=\'text\'], #option_'+product_id+' input[type=\'radio\']:checked, #option_'+product_id+' input[type=\'checkbox\']:checked, #option_'+product_id+' select, #option_'+product_id+' textarea');
					$.ajax({
							url: 'index.php?route=checkout/cart/add',
							type: 'post',
							data: data.serialize() + '&product_id=' + product_id,
							dataType: 'json',
							beforeSend: function(){
							},
								success: function(json) {
									$('.success, .warning, .attention, information, .error').remove();
									if (json['error']) {
										if (json['error']['warning']) {
											$('#notification').html('<div class="warning" style="display: none;">' + json['error']['warning'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
										
											$('.warning').fadeIn('slow');
										}
										
										for (i in json['error']) {
											$('#option-' + i).after('<span class="error">' + json['error'][i] + '</span>');
										}
									}	 
												
									if (json['success']) {
										$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
					
										$('.success').fadeIn('slow');
					
										$('#cart-total').html(json['total']);
				
										$('html, body').animate({ scrollTop: 0 }, 'slow'); 
									}	
								}
						});
				}
				</script>			
		<script type="text/javascript"><!--
$('.plus').click(function() {

              var text1 = parseInt( $('.buton_input:first', $(this).parent()).children('input').val()) + 1;
              $('.buton_input:first', $(this).parent()).children('input').val(text1);   
              
              var text1 = parseInt( $('.az_input2:first', $(this).parent()).children('input').val()) + 1;
              $('.input2:first', $(this).parent()).children('input').val(text1);   
          
        }); 
        
        $('.minus').click(function(){
    
    
        var text = parseInt( $('.buton_input:first', $(this).parent()).children('input').val()) - 1;
            if ( parseInt(text) >= 0 ){
          $('.buton_input:first', $(this).parent()).children('input').val(text);   
            }
            
              var text = parseInt( $('.az_input2:first', $(this).parent()).children('input').val()) - 1;
            if ( parseInt(text) >= 0 ){
          $('.input2:first', $(this).parent()).children('input').val(text);   
            }
        });

function addQtyToCart(product_id) {
  var qty = $('.item-' + product_id).val();
  if ((parseFloat(qty) != parseInt(qty)) || isNaN(qty)) {
		qty = 1;
  }
  addToCart(product_id, qty);
}


$('.colorbox').colorbox({
	overlayClose: true,
	opacity: 0.5
});
//--></script> 

Мой common.js

$(document).ready(function() {
	/* Search */
	$('.button-search').bind('click', function() {
		url = $('base').attr('href') + 'index.php?route=product/search';
				 
		var filter_name = $('input[name=\'filter_name\']').attr('value');
		
		if (filter_name) {
			url += '&filter_name=' + encodeURIComponent(filter_name);
		}
		
		location = url;
	});
	
	$('#header input[name=\'filter_name\']').bind('keydown', function(e) {
		if (e.keyCode == 13) {
			url = $('base').attr('href') + 'index.php?route=product/search';
			 
			var filter_name = $('input[name=\'filter_name\']').attr('value');
			
			if (filter_name) {
				url += '&filter_name=' + encodeURIComponent(filter_name);
			}
			
			location = url;
		}
	});
	
	/* Ajax Cart */
	$('#cart > .heading a').live('click', function() {
		$('#cart').addClass('active');
		
		$('#cart').load('index.php?route=module/cart #cart > *');
		
		$('#cart').live('mouseleave', function() {
			$(this).removeClass('active');
		});
	});
	
	/* Mega Menu */
	$('#menu ul > li > a + div').each(function(index, element) {
		// IE6 & IE7 Fixes
		if ($.browser.msie && ($.browser.version == 7 || $.browser.version == 6)) {
			var category = $(element).find('a');
			var columns = $(element).find('ul').length;
			
			$(element).css('width', (columns * 143) + 'px');
			$(element).find('ul').css('float', 'left');
		}		
		
		var menu = $('#menu').offset();
		var dropdown = $(this).parent().offset();
		
		i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth());
		
		if (i > 0) {
			$(this).css('margin-left', '-' + (i + 5) + 'px');
		}
	});

	// IE6 & IE7 Fixes
	if ($.browser.msie) {
		if ($.browser.version <= 6) {
			$('#column-left + #column-right + #content, #column-left + #content').css('margin-left', '195px');
			
			$('#column-right + #content').css('margin-right', '195px');
		
			$('.box-category ul li a.active + ul').css('display', 'block');	
		}
		
		if ($.browser.version <= 7) {
			$('#menu > ul > li').bind('mouseover', function() {
				$(this).addClass('active');
			});
				
			$('#menu > ul > li').bind('mouseout', function() {
				$(this).removeClass('active');
			});	
		}
	}
	
	$('.success img, .warning img, .attention img, .information img').live('click', function() {
		$(this).parent().fadeOut('slow', function() {
			$(this).remove();
		});
	});	
});

function getURLVar(urlVarName) {
	var urlHalves = String(document.location).toLowerCase().split('?');
	var urlVarValue = '';
	
	if (urlHalves[1]) {
		var urlVars = urlHalves[1].split('&');

		for (var i = 0; i <= (urlVars.length); i++) {
			if (urlVars[i]) {
				var urlVarPair = urlVars[i].split('=');
				
				if (urlVarPair[0] && urlVarPair[0] == urlVarName.toLowerCase()) {
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	
	return urlVarValue;
} 

function addToCart(product_id, quantity) {
	quantity = typeof(quantity) != 'undefined' ? quantity : 1;

	$.ajax({
		url: 'index.php?route=checkout/cart/add',
		type: 'post',
		data: 'product_id=' + product_id + '&quantity=' + quantity,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information, .error').remove();
			
			if (json['redirect']) {
				location = json['redirect'];
			}
			
			if (json['success']) {
				$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
				
				$('.success').fadeIn('slow');
				
				$('#cart-total').html(json['total']);
				
			}	
		}
	});
}
function addToWishList(product_id) {
	$.ajax({
		url: 'index.php?route=account/wishlist/add',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();
						
			if (json['success']) {
				$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
				
				$('.success').fadeIn('slow');
				
				$('#wishlist-total').html(json['total']);
				
			}	
		}
	});
}

function addToCompare(product_id) { 
	$.ajax({
		url: 'index.php?route=product/compare/add',
		type: 'post',
		data: 'product_id=' + product_id,
		dataType: 'json',
		success: function(json) {
			$('.success, .warning, .attention, .information').remove();
						
			if (json['success']) {
				$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
				
				$('.success').fadeIn('slow');
				
				$('#compare-total').html(json['total']);
				
			}
		}
	});
}

Контроллекр модуля категории во вкладках

 

class ControllerModulerandprod extends Controller {
protected $category_id = 0;
protected $path = array();

protected function index($setting) {
$this->language->load('module/randprod');
static $module = 0;
static $inc_js = 0;
$this->data['heading_title'] = $this->language->get('heading_title');
$this->data['button_cart'] = $this->language->get('button_cart');
$this->data['text_select'] = $this->language->get('text_select');

$this->load->model('tool/image');
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$categories = $this->getCategoriesBySort($setting['categories']);

$this->data['categories'] = array();


if (isset($setting['limit_carousel']) && $setting['limit_carousel']) {
$this->data['limit_carousel'] = $setting['limit_carousel'];
} else {
$this->data['limit_carousel'] = 5;
}

if (isset($setting['wrap_carousel']) && $setting['wrap_carousel']) {
$this->data['wrap_carousel'] = $setting['wrap_carousel'];
} else {
$this->data['wrap_carousel'] = false;
}

if (isset($setting['auto_carousel']) && $setting['auto_carousel']) {
$this->data['auto_carousel'] = $setting['auto_carousel'];
} else {
$this->data['auto_carousel'] = false;
}

foreach ($categories as $category) {

$category_info = $this->model_catalog_category->getCategory($category);
if (!$category_info) continue;
$this->data['categories'][$category]['name'] = $category_info['name'];
$this->data['categories'][$category]['category_id'] = $category;
$this->data['categories'][$category]['href'] = $this->url->link('product/category', 'path=' . $category);
$sort = false;
$order = false;
$products = array();
if (isset($setting['sort']) && $setting['sort']) {
if ($setting['sort']=="bestseller") {
$this->load->model('module/randprod');
$results = $this->model_module_randprod->getBestSellerProductsByCategoryId($setting['limit'],$category);
} else {
$s = explode("-",$setting['sort']);
$sort = $s[0];
$order = $s[1];

$data = array(
'filter_category_id' => $category,
'start' => 0,
'limit' => $setting['limit'],
'sort' => $sort,
'order' => $order
);
$results = $this->model_catalog_product->getProducts($data);
}
}
foreach ($results as $result) {
if ($result['image']) {
$image = $this->model_tool_image->resize($result['image'], $setting['image_width'], $setting['image_height']);
} else {
$image = false;
}

if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
$price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
} else {
$price = false;
}

if ((float)$result['special']) {
$special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')));
} else {
$special = false;
}

if ($this->config->get('config_review_status')) {
$rating = $result['rating'];
} else {
$rating = false;
}
$product_options = array();

foreach ($this->model_catalog_product->getProductOptions($result['product_id']) as $option) {
if ($option['type'] == 'select' || $option['type'] == 'radio' || $option['type'] == 'checkbox' || $option['type'] == 'image') {
$option_value_data = array();

foreach ($option['option_value'] as $option_value) {
if (!$option_value['subtract'] || ($option_value['quantity'] > 0)) {
if ((($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) && (float)$option_value['price']) {
$price = $this->currency->format($this->tax->calculate($option_value['price'], $result['tax_class_id'], $this->config->get('config_tax')));
} else {
$price = false;
}

$option_value_data[] = array(
'product_option_value_id' => $option_value['product_option_value_id'],
'option_value_id' => $option_value['option_value_id'],
'name' => $option_value['name'],
'image' => $this->model_tool_image->resize($option_value['image'], 50, 50),
'price' => $price,
'price_prefix' => $option_value['price_prefix']
);
}
}

$product_options[] = array(
'product_option_id' => $option['product_option_id'],
'option_id' => $option['option_id'],
'name' => $option['name'],
'type' => $option['type'],
'option_value' => $option_value_data,
'required' => $option['required']
);
} elseif ($option['type'] == 'text' || $option['type'] == 'textarea' || $option['type'] == 'file' || $option['type'] == 'date' || $option['type'] == 'datetime' || $option['type'] == 'time') {
$product_options[] = array(
'product_option_id' => $option['product_option_id'],
'option_id' => $option['option_id'],
'name' => $option['name'],
'type' => $option['type'],
'option_value' => $option['option_value'],
'required' => $option['required']
);
}
}

$products[] = array(

'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'options' => $product_options,

'price' => $price,
'special' => $special,
'rating' => $rating,
'reviews' => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
'href' => $this->url->link('product/product', 'product_id=' . $result['product_id'])
);


}

//foreach products
$this->data['categories'][$category]['products'] = $products;
}//foreach categories


$this->data['module'] = $module++;

if (isset($setting['carousel']) && $setting['carousel']==1 && $inc_js==0) {
$inc_js=1;
$this->document->addScript('catalog/view/javascript/jquery/jquery.jcarousel.min.js');
$this->document->addStyle('catalog/view/theme/' . $this->config->get('config_template') . '/stylesheet/carousel.css');
}

if (isset($setting['carousel']) && $setting['carousel']==1) {
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/randprod_carousel.tpl')) {
$this->template = $this->config->get('config_template') . '/template/module/randprod_carousel.tpl';
} else {
$this->template = 'default/template/module/randprod_carousel.tpl';
}
} else {
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/randprod.tpl')) {
$this->template = $this->config->get('config_template') . '/template/module/randprod.tpl';
} else {
$this->template = 'default/template/module/randprod.tpl';
}
}


$this->render();
}

private function getCategoriesBySort($categories){

$data = array();
if ($categories) {
$query = $this->db->query("SELECT category_id FROM " . DB_PREFIX . "category c WHERE category_id in (".implode(",",$categories).") ORDER BY c.sort_order");

foreach ($query->rows as $row) {
$data[]=$row['category_id'];
}
}
return $data;
}

}

?>

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
You are posting as a guest. If you have an account, please sign in.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

×

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.