Commit ec957aa41ecb7f6c2210c28a0d2a9d2971389b32

Authored by Volodymyr
1 parent 45ba031d

product modal js

Showing 1 changed file with 72 additions and 0 deletions   Show diff stats
frontend/web/js/product.js
  1 +var phoneInput = document.querySelector('#cardProduct [type="tel"]');
  2 +var counter = document.querySelector('#cardProduct .product-counter__input');
  3 +
  4 +if (phoneInput) {
  5 + phoneInput.addEventListener('input', phoneHandleInput);
  6 +}
  7 +
  8 +if (counter) {
  9 + counterFunc(counter);
  10 +}
  11 +
  12 +function phoneHandleInput(e) {
  13 + e.target.value = phoneMasks(e.target.value);
  14 +}
  15 +
  16 +function phoneMasks(phone) {
  17 + return phone.replace(/\D/g, '')
  18 + .replace(/^(\d)/, '($1')
  19 + .replace(/^(\(\d{3})(\d)/, '$1) $2')
  20 + .replace(/(\d{3})(\d{1,7})/, '$1-$2')
  21 + .replace(/(-\d{2})(\d{1,7})/, '$1-$2')
  22 + .replace(/(-\d{2})\d+?$/, '$1');
  23 +}
  24 +
  25 +function counterFunc(counter) {
  26 + let itemPrice = counter.parentElement.querySelector('.product-counter__value');
  27 + itemPrice.innerHTML = `${itemPrice.dataset.price} ${itemPrice.dataset.currency}`;
  28 +
  29 + counter.querySelector('input').value = 1;
  30 + counter.addEventListener('input', counterHandleInput);
  31 + counter.addEventListener('change', counterHandleChange);
  32 + counter.querySelector('.product-counter__increment').addEventListener('click', increment);
  33 + counter.querySelector('.product-counter__decrement').addEventListener('click', decrement);
  34 +
  35 + function counterHandleInput(e) {
  36 + e.target.value = e.target.value.replace(/\D/g, '');
  37 + updateSummary();
  38 + }
  39 +
  40 + function counterHandleChange(e) {
  41 + const value = e.target.value.replace(/\D/g, '');
  42 + if (value == 0) {
  43 + e.target.value = 1;
  44 + }
  45 + updateSummary();
  46 + }
  47 +
  48 + function increment(e) {
  49 + e.preventDefault();
  50 + const value = Number(counter.querySelector('input').value);
  51 + counter.querySelector('input').value = value + 1;
  52 + updateSummary();
  53 + }
  54 +
  55 + function decrement(e) {
  56 + e.preventDefault();
  57 + const value = Number(counter.querySelector('input').value);
  58 + if (value > 1) {
  59 + counter.querySelector('input').value = value - 1;
  60 + updateSummary();
  61 + }
  62 + }
  63 +
  64 + function updateSummary() {
  65 + const amount = counter.querySelector('input').value;
  66 + if (amount >= 1) {
  67 + const oldSum = Number(itemPrice.dataset.price) * 10;
  68 + const newSum = String(oldSum * amount);
  69 + itemPrice.innerHTML = `${newSum.slice(0, -2)}.${newSum.slice(-2)} ${itemPrice.dataset.currency}`;
  70 + }
  71 + }
  72 +}
0 73 \ No newline at end of file
... ...