Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

Как сгделать поле выпотому чтора когдачества товара, чтобы оно добавляло нужное когдачество в корзину при покупки.


Recommended Posts

Здравствуйте, возникла необходимость в добавлении поля выпотому чтора когдачества товара в модуле вариантов товара, саму кнопку добавления покупки товара я сгделал, но возикла проблема с выпотому чтором когдачества и добавления этого когдачества в корзину.

Не хочет отправлять нужное когдачество в корзину

код модуля с  кнопкой 

<div class="prodvar-button">
 <div class="form-group">
              <label class="control-label" for="input-quantity">{{ entry_qty }}</label>
<div class="input-group number-spinner">
			      <span class="input-group-btn">
					<button class="btn btn-default" data-dir="dwn"><i class="fa fa-minus"></i></button>
			      </span>
				<input type="text" name="quantity" value="{{ product['minimum'] }}" id="input-quantity" class="form-control text-center" />
				  <span class="input-group-btn">
					<button class="btn btn-default" data-dir="up"><i class="fa fa-plus"></i></button>
				  </span>
			    </div>
              
              <input type="hidden" name="product_id" value="{{ product['product_id'] }}" />
              <br />
              <button type="button" id="button-cart" data-loading-text="{{ text_loading }}" class="btn btn-primary btn-lg btn-block">{{ button_cart }}</button>
            </div>

</div>

В кнопку 

				<button type="button" id="button-cart" class="btn btn-primary btn-lg btn-block">{{ button_cart }}</button>

  добавлял атрибут

onclick="cart.add('{{ product['product_id'] }}', $(this).parent().parent().find('.quantity_input').val());"

рилиило только с 

onclick="cart.add('{{ product['product_id'] }}', {{ product['minimum'] }}

но добавлял только 1 товар

код для переключалки когдачества 

	$(document).on('click', '.number-spinner button', function () {
var btn = $(this),
oldValue = btn.closest('.number-spinner').find('input').val().trim(),
newVal = 1;

if (btn.attr('data-dir') == 'up') {
newVal = parseInt(oldValue) + 1;
} else {
if (oldValue > 1) {
newVal = parseInt(oldValue) - 1;
} else {
newVal = 1;
}
} btn.closest('.number-spinner').find('input').val(newVal);
});

Как сгделать ик чтобы было синдартное поле как с правой стороны и оно агдекватно рилиило? 

в игдено нужно чтоб оно отправляло данные в попап корзину, с блоком справа код ниже рилииет

 $(function() {
            $.ajax({
              type: 'get',
              url:  'index.php?route=extension/module/cart_popup/initcart',
              dataType: 'json',
              cache: false,
              success: function(json) {
                $.each($("[onclick^='"+json['add_function_selector']+"']"), function() {
                  var product_id = $(this).attr('onclick').match(/[0-9]+/);
                    $(this)
                    .attr('onclick', 'call_cp(\'' + $(this).attr('onclick').match(/[0-9]+/) + '\',\'' + 'add' + '\');')
                    .addClass('cp-call-button');
                });
                var product_id_in_page = $("input[name='product_id']").val();
                  $('#'+json['add_id_selector'])
                  .unbind('click')
                  .attr('onclick', 'call_cp(\'' + product_id_in_page + '\',\'' + 'add_option' + '\');');

                if (json['cart_products']) {
                  $.each(json['cart_products'], function(i,value) {
                    $('[onclick="call_cp(\'' + value + '\',\'' + 'add' + '\');"]')
                    .html('<i class="fa fa-shopping-cart"></i> <span class="hidden-xs hidden-sm hidden-md">' + json['text_in_cart'] + '</span>')
                    .attr('onclick', 'call_cp(\'' + value + '\',\'' + 'load' + '\');');
                    $('[onclick="call_cp(\'' + value + '\',\'' + 'add_option' + '\');"]')
                    .html(json['text_in_cart'])
                    .attr('onclick', 'call_cp(\'' + value + '\',\'' + 'load_option' + '\');');
                  });
                }
                if (json['cart_products_vs_options']) {
                  $.each(json['cart_products_vs_options'], function(i,value) {
                    $('[onclick="call_cp(\'' + value + '\',\'' + 'add' + '\');"]')
                    .html('<i class="fa fa-shopping-cart"></i> <span class="hidden-xs hidden-sm hidden-md">' + json['text_in_cart'] + '</span>');
                    $('[onclick="call_cp(\'' + value + '\',\'' + 'add_option' + '\');"]')
                    .html(json['text_in_cart_vs_options']);
                  });
                }
              }
            });
          });
          function call_cp(product_id, action) {
            quantity = typeof(quantity) != 'undefined' ? quantity : 1;
            if (action == "add") {
              $.ajax({
                url: 'index.php?route=checkout/cart/add',
                type: 'post',
                data: 'product_id=' + product_id + '&quantity=' + quantity,
                dataType: 'json',
                cache: false,
                success: function(json) {
                  if (json['redirect']) {
                    location = json['redirect'];
                  }
                  if (json['success']) {
                    cpInit();
                    call_cp(product_id,'load');
                    $('#cart-total').html(json['total']);
                  }
                }
              });
            }

            if (action == "load" || action == "load_option") {
              $.magnificPopup.open({
                tLoading: '<img src="catalog/view/theme/default/stylesheet/cart_popup/loading.svg" alt="" />',
                items: {
                  src: 'index.php?route=extension/module/cart_popup',
                  type: 'ajax'
                },
                showCloseBtn: false
              });
              $('.mfp-bg').css({
                'background': 'url(image/cart_popup/background/{{ cp_setting['style_beckground'] }})',
                'opacity': '{% if cp_setting['background_opacity'] == 0 %}{{ cp_setting['background_opacity'] }}{% else %}{{ cp_setting['background_opacity']/10 }}{% endif %}'
              });
            }

            if (action == "add_option") {
              $.ajax({
                url: 'index.php?route=checkout/cart/add',
                type: 'post',
                data: $('#product input[type=\'text\'], #product input[type=\'hidden\'], #product input[type=\'radio\']:checked, #product input[type=\'checkbox\']:checked, #product select, #product textarea'),
                dataType: 'json',
                cache: false,
                beforeSend: function() {
                  $('#button-cart').button('loading');
                },
                complete: function() {
                  $('#button-cart').button('reset');
                },
                success: function(json) {
                  $('.alert, .text-danger').remove();
                  $('.form-group').removeClass('has-error');

                  if (json['error']) {
                    if (json['error']['option']) {
                      for (i in json['error']['option']) {
                        var element = $('#input-option' + i.replace('_', '-'));

                        if (element.parent().hasClass('input-group')) {
                          element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
                        } else {
                          element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
                        }
                      }
                    }
                    $('.text-danger').parent().addClass('has-error');
                  }
                  if (json['success']) {
                    cpInit();
                    call_cp(product_id, 'load_option');
                    $('#cart-total').html(json['total']);
                  }
                }
              });
            }
          }

 

подскажите пожалуйси что я не ик сгделал? и как мне это полинить? Благодарю

Link to comment
Share on other sites


  • 3 weeks later...
В 06.06.2021 в 22:20, WeBuy сказал:

<input type="text" name="quantity" value="{{ product['minimum'] }}" id="input-quantity" class="form-control text-center" />

 

<input type="text" name="quantity_{{ product['product_id'] }}" value="{{ product['minimum'] }}" id="input-quantity-{{ product['product_id'] }}" class="form-control text-center" />

 

В 06.06.2021 в 22:20, WeBuy сказал:

<button type="button" id="button-cart" class="btn btn-primary btn-lg btn-block">{{ button_cart }}</button>

 

 

<button data-id="{{ product['product_id'] }}" type="button" class="add-variant-to-cart btn btn-primary btn-lg btn-block">{{ button_cart }}</button>

 

$(function(){
    $('.add-variant-to-cart').click(function(){
        let product_id = $(this).attr('data-id');
        let quantity = $('#input-quantity-' + product_id);

        cart.add(product_id, quantity);

    })
})

 

Link to comment
Share on other sites

  • 1 month later...
В 23.06.2021 в 17:56, fanatic сказал:

 

<input type="text" name="quantity_{{ product['product_id'] }}" value="{{ product['minimum'] }}" id="input-quantity-{{ product['product_id'] }}" class="form-control text-center" />

 

 

 

<button data-id="{{ product['product_id'] }}" type="button" class="add-variant-to-cart btn btn-primary btn-lg btn-block">{{ button_cart }}</button>

 

$(function(){
    $('.add-variant-to-cart').click(function(){
        let product_id = $(this).attr('data-id');
        let quantity = $('#input-quantity-' + product_id);

        cart.add(product_id, quantity);

    })
})

 

Сгделал как вы подсказали, но в корзину не падают товары, точнее падают но сразу пропадают

Link to comment
Share on other sites


Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

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.