<!-- Скрипт ограничения кол-ва товаров в корзине при выборе определенного типа доставки -->
<script>
// максимально допустимое кол-во товаров для указанного способа доставки
const sd_maxItemsCount = 3
// идентификатор способа доставки, ради которого вот это вот все
// (можно посмотреть в URL страницы настроек способа доставки, значение параметра integid)
let sd_targetDeliveryId = '1660466412'
// сообщение об ограничении
// #max# будет заменено на значение из sd_maxItemsCount
// #cur# будет заменено на текущее кол-во товаров в корзине
const sd_errorMessage = 'Для выбранного способа доставки максимальное количество товаров - #max#<br>' +
'Сейчас товаров - #cur#<br>Пожалуйста, уменьшите количество товаров, либо измените способ доставки'
$(document).ready(function () {
const sd_Sel = {
mainObj: '.t706__cartwin',
mainObjActive: '.t706__cartwin_showed',
deliveriesObj: '#delivery-services-wrapper',
itemsWrapper: '.t706__cartwin-products',
cartItem: '.t706__product',
itemQuantity: '.t706__product-quantity',
inputDeliveryType: '[name="tildadelivery-type"]',
errorWrapper: '.sd-error',
errorBefore: '.t706__cartwin-prodamount-label, #addresses-wrapper',
cartSubmitBtn: '.t706__cartwin .t-submit'
}
let sd_cartObj = $(sd_Sel.mainObj)
let sd_currentDeliveryId = null
let sd_currentItemsCount = 0
sd_targetDeliveryId = parseInt(sd_targetDeliveryId)
// проверяем текущий способ доставки на соответствие заданному
function sd_isTargetDeliveryType() {
sd_currentDeliveryId = parseInt($(sd_Sel.inputDeliveryType).filter(':checked').data('serviceId'))
return sd_targetDeliveryId === sd_currentDeliveryId
}
// считает суммарное количество едениц товаров в корзине
function sd_getTotalItemsCount() {
let itemsQuantity = 0
sd_cartObj.find(sd_Sel.itemQuantity).each(function(){
let q = parseInt($(this).text())
if (!isNaN(q)) itemsQuantity += q
})
return itemsQuantity
}
// накладывает ограничение в случае превышения допустимого кол-ва товаров
// в противном случае снимает ограничение
function sd_checkTotalItemsCount() {
sd_currentItemsCount = sd_getTotalItemsCount()
if (sd_currentItemsCount > sd_maxItemsCount) {
sd_SetError()
} else {
sd_UnsetError()
}
}
// выводим ошибку, блокируем форму
function sd_SetError() {
let errorSiblings = $(sd_Sel.errorBefore)
errorSiblings.each(function(){
let errorWrapper = $(this).siblings(sd_Sel.errorWrapper)
if (errorWrapper.length === 0) {
$(this).before(<div class="${sd_Sel.errorWrapper.substr(1)}">${sd_ErrorMessage()}</div>)
} else {
errorWrapper.html(sd_ErrorMessage())
}
})
$(sd_Sel.cartSubmitBtn).attr('type', 'button').attr('disabled', true);
}
// убираем ошибку, разблокируем форму
function sd_UnsetError() {
$(sd_Sel.errorWrapper).remove()
$(sd_Sel.cartSubmitBtn).attr('type', 'submit').removeAttr('disabled');
}
// форматирует сообщение об ошибке
function sd_ErrorMessage() {
return sd_errorMessage
.replace('#max#', sd_maxItemsCount)
.replace('#cur#', sd_currentItemsCount)
}
// проверяем все
function sd_CheckAll() {
// выбранный способ доставки совпадает с заданным?
if (sd_isTargetDeliveryType()) {
// тогда запускаем проверку количества товаров
sd_checkTotalItemsCount()
} else {
// инчае убираем сообщение об ошибке, если было выведено ранее
sd_UnsetError()
}
}
// отслеживание изменения способа доставки
$(document).on('change', sd_Sel.inputDeliveryType, function(){
sd_CheckAll()
})
// общий обработчик для открытия корзины и изменения кол-ва товаров
let sd_Observer = new MutationObserver(function (e) {
// открытие корзины
if (e[0].type === 'attributes') {
if (e[0].target.classList.contains(sd_Sel.mainObjActive.substr(1))) {
sd_CheckAll()
// отслеживание добавления/удаления товаров
let sd_itemsObj = $(sd_Sel.itemsWrapper)
if (sd_itemsObj.length > 0) {
sd_Observer.observe(sd_itemsObj[0], {
attributes: false,
subtree: true,
characterData: true,
childList: true,
})
}
}
}
// добавление/удаление и изменение кол-ва товаров
else {
sd_CheckAll()
}
})
// отслеживание открытия корзины
if (sd_cartObj.length > 0) {
sd_Observer.observe(sd_cartObj[0], {
attributes: true,
attributeFilter: ['class'],
})
}
})
</script>
<style>
.sd-error {
border: 1px solid red;
color: red;
background-color: #ffe6c6;
padding: .5rem 1rem;
font-family: 'FuturaPT',Arial,sans-serif;
font-weight: normal;
text-align: left;
font-size: 13px;
margin: .5rem 0;
}
</style>