From ec957aa41ecb7f6c2210c28a0d2a9d2971389b32 Mon Sep 17 00:00:00 2001 From: vova Date: Mon, 9 May 2022 20:11:22 +0300 Subject: [PATCH] product modal js --- frontend/web/js/product.js | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+), 0 deletions(-) diff --git a/frontend/web/js/product.js b/frontend/web/js/product.js index e69de29..893a392 100644 --- a/frontend/web/js/product.js +++ b/frontend/web/js/product.js @@ -0,0 +1,72 @@ +var phoneInput = document.querySelector('#cardProduct [type="tel"]'); +var counter = document.querySelector('#cardProduct .product-counter__input'); + +if (phoneInput) { + phoneInput.addEventListener('input', phoneHandleInput); +} + +if (counter) { + counterFunc(counter); +} + +function phoneHandleInput(e) { + e.target.value = phoneMasks(e.target.value); +} + +function phoneMasks(phone) { + return phone.replace(/\D/g, '') + .replace(/^(\d)/, '($1') + .replace(/^(\(\d{3})(\d)/, '$1) $2') + .replace(/(\d{3})(\d{1,7})/, '$1-$2') + .replace(/(-\d{2})(\d{1,7})/, '$1-$2') + .replace(/(-\d{2})\d+?$/, '$1'); +} + +function counterFunc(counter) { + let itemPrice = counter.parentElement.querySelector('.product-counter__value'); + itemPrice.innerHTML = `${itemPrice.dataset.price} ${itemPrice.dataset.currency}`; + + counter.querySelector('input').value = 1; + counter.addEventListener('input', counterHandleInput); + counter.addEventListener('change', counterHandleChange); + counter.querySelector('.product-counter__increment').addEventListener('click', increment); + counter.querySelector('.product-counter__decrement').addEventListener('click', decrement); + + function counterHandleInput(e) { + e.target.value = e.target.value.replace(/\D/g, ''); + updateSummary(); + } + + function counterHandleChange(e) { + const value = e.target.value.replace(/\D/g, ''); + if (value == 0) { + e.target.value = 1; + } + updateSummary(); + } + + function increment(e) { + e.preventDefault(); + const value = Number(counter.querySelector('input').value); + counter.querySelector('input').value = value + 1; + updateSummary(); + } + + function decrement(e) { + e.preventDefault(); + const value = Number(counter.querySelector('input').value); + if (value > 1) { + counter.querySelector('input').value = value - 1; + updateSummary(); + } + } + + function updateSummary() { + const amount = counter.querySelector('input').value; + if (amount >= 1) { + const oldSum = Number(itemPrice.dataset.price) * 10; + const newSum = String(oldSum * amount); + itemPrice.innerHTML = `${newSum.slice(0, -2)}.${newSum.slice(-2)} ${itemPrice.dataset.currency}`; + } + } +} \ No newline at end of file -- libgit2 0.21.4