-
-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathchange_be_variant.js
More file actions
49 lines (42 loc) · 1.82 KB
/
Copy pathchange_be_variant.js
File metadata and controls
49 lines (42 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { dispatchCustomEvent } from './helper/dispatch_custom_event';
document.addEventListener('DOMContentLoaded', () => {
function setValue (parentElement, targetElementClass, spanClass, value) {
const targetElement = parentElement.querySelector(targetElementClass);
if (targetElement) {
const spanElement = targetElement.querySelector(spanClass);
if (typeof (value) === 'undefined') {
spanElement.innerHTML = ' ';
return;
}
if (spanClass !== '.stock') {
spanElement.innerHTML = value;
} else {
const template = Number(value) === 1 ? spanElement.dataset.stockSingular : spanElement.dataset.stockPlural;
const placeholder = '%1$s';
const text = template.replace(placeholder, value);
spanElement.innerHTML = text;
}
}
}
const productPrice = document.querySelector('#product-price');
document.querySelector('#be-variants-select')
.addEventListener('change', function changePriceAndDiscountBasedOnCustomerChoice () {
const selectedOption = this.selectedOptions[0];
const { specialPrice } = selectedOption.dataset;
const { regularPrice } = selectedOption.dataset;
const { specialPricePercentageDiscount } = selectedOption.dataset;
const { availableStock } = selectedOption.dataset;
setValue(productPrice, '.special_price', '.price', specialPrice);
setValue(productPrice, '.regular_price', '.price', regularPrice);
setValue(productPrice, '.special_price_percentage_discount', '.price', specialPricePercentageDiscount);
setValue(productPrice, '.available_stock', '.stock', availableStock);
dispatchCustomEvent(
'extcode:be-variant-was-changed',
{
specialPrice,
regularPrice,
specialPricePercentageDiscount
}
);
});
});