Now I have the following code for the popup product spec and quantity selection modal:
With following JavaScript:
(document).ready(function () {
const modal = ('#product-spec-modal');
const variantsContainer = modal.find('#variants-container');
const qtyInput = modal.find('#modal-qty');
const qtyMinusBtn = modal.find('.qty-minus');
const qtyPlusBtn = modal.find('.qty-plus');
const modalCloseBtn = modal.find('.modal-close');
const modalForm = modal.find('#product-spec-form');
const modalError = modal.find('.modal-error');
let currentProductData = null;
let activeAddToCartBtn = null; // store clicked button to restore UI
function buildVariantOptions(variants) {
if (!Array.isArray(variants) || variants.length === 0) {
variantsContainer.html('');
return;
}
// Trim and split attr_name
const attrNames = variants[0].attr_name ? variants[0].attr_name.split(',').map(s => s.trim()) : [];
if (attrNames.length === 0) {
variantsContainer.html('');
return;
}
let attrValuesByName = {};
attrNames.forEach(attr => attrValuesByName[attr] = new Set());
variants.forEach(variant => {
// Use variant_values field instead of attr_value
if (!variant.variant_values) return; // variant_values is your actual attribute values string
// Split and trim variant_values
const vals = variant.variant_values.split(',').map(s => s.trim());
vals.forEach((val, i) => {
if (attrNames[i]) attrValuesByName[attrNames[i]].add(val);
});
});
if (Object.values(attrValuesByName).every(set => set.size === 0)) {
variantsContainer.html(''); // no options found
return;
}
let html = '';
attrNames.forEach((attrName, groupIndex) => {
html += `<div class="variant-group" data-variant-attribute="${attrName}">
<label class="variant-label">${attrName}:</label>
<div class="variant-options" role="radiogroup" aria-label="${attrName} options">`;
Array.from(attrValuesByName[attrName]).forEach((val, optionIndex) => {
const optionId = `variant-${attrName}-${optionIndex}`;
html += `
<label class="variant-option" for="${optionId}" tabindex="0" role="radio" aria-checked="false" data-variant-attr="${attrName}" data-variant-val="${val}">
<input type="radio" name="variant-${attrName}" id="${optionId}" value="${val}">
${val}
</label>`;
});
html += '</div></div>';
});
variantsContainer.html(html);
function updateSelectedStyles() {
variantsContainer.find('.variant-option').each(function () {
var label = $(this);
var input = label.find('input[type="radio"]');
if (input.prop('checked')) {
label.addClass('selected').attr('aria-checked', 'true');
} else {
label.removeClass('selected').attr('aria-checked', 'false');
}
});
}
updateSelectedStyles();
variantsContainer.find('.variant-option').on('click', function () {
var input = $(this).find('input[type="radio"]');
input.prop('checked', true).trigger('change');
updateSelectedStyles();
}).on('keydown', function (e) {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
$(this).trigger('click');
}
});
variantsContainer.find('input[type="radio"]').on('change', updateSelectedStyles);
}
function openModal(productData, clickedBtn) {
currentProductData = productData;
activeAddToCartBtn = clickedBtn;
// If product has multiple variants, build variant selectors
if (productData.hasMultipleVariants) {
buildVariantOptions(productData.variants);
variantsContainer.show();
} else {
// Single variant: no variant selection UI needed
variantsContainer.hide().html('');
}
// Set quantity input attributes
const min = Number(productData.min) || 1;
const step = Number(productData.step) || 1;
const max = Number(productData.max) || null;
qtyInput.attr('min', min);
qtyInput.attr('step', step);
qtyInput.val(min);
if (max) {
qtyInput.attr('max', max);
} else {
qtyInput.removeAttr('max');
}
modalError.text('');
modal.fadeIn(200);
$('body').css('overflow', 'hidden');
//qtyInput.focus();
}
function closeModal() {
modal.fadeOut(200);
$('body').css('overflow', '');
currentProductData = null;
activeAddToCartBtn = null;
variantsContainer.html('');
modalError.text('');
}
qtyMinusBtn.on('click', function () {
let val = parseInt(qtyInput.val()) || 1;
const min = parseInt(qtyInput.attr('min')) || 1;
const step = parseInt(qtyInput.attr('step')) || 1;
val = Math.max(min, val - step);
qtyInput.val(val);
});
qtyPlusBtn.on('click', function () {
let val = parseInt(qtyInput.val()) || 1;
const step = parseInt(qtyInput.attr('step')) || 1;
const max = parseInt(qtyInput.attr('max'));
val = val + step;
if (!isNaN(max)) val = Math.min(max, val);
qtyInput.val(val);
});
qtyInput.on('input', function () {
let val = +qtyInput.val();
const min = +qtyInput.attr('min');
const max = +qtyInput.attr('max');
const step = +qtyInput.attr('step');
if (isNaN(val) || val < min) val = min;
if (!isNaN(max) && val > max) val = max;
if (step > 1) val = Math.round(val / step) * step;
qtyInput.val(val);
});
modalCloseBtn.on('click', closeModal);
modal.on('click', function (e) {
if (e.target === this) closeModal();
});
modalForm.on('submit', function (e) {
e.preventDefault();
modalError.text('');
if (!currentProductData) {
modalError.text('產品資料缺失');
return;
}
// Check all variant groups have selection
let selectedAttributes = {};
let valid = true;
variantsContainer.find('.variant-group').each(function () {
const attrName = $(this).data('variant-attribute');
const checkedInput = $(this).find('input[type=radio]:checked');
if (checkedInput.length === 0) {
modalError.text(`請選擇${attrName}`);
valid = false;
return false; // break each loop
}
selectedAttributes[attrName] = checkedInput.val();
});
if (!valid) return;
// Validate qty
let qty = parseInt(qtyInput.val());
const minQty = Number(currentProductData.min) || 1;
const maxQty = Number(currentProductData.max);
if (isNaN(qty) || qty < minQty) {
modalError.text(`數量不能小於 ${minQty}`);
return;
}
if (!isNaN(maxQty) && maxQty > 0 && qty > maxQty) {
modalError.text(`數量不能超過最大限制 ${maxQty}`);
return;
}
// Find matching variant
let matchedVariant = null;
if (currentProductData.hasMultipleVariants) {
matchedVariant = currentProductData.variants.find(variant => {
if (!variant.attr_name || !variant.variant_values) return false;
const attrNames = variant.attr_name.split(',').map(s => s.trim());
const attrValues = variant.variant_values.split(',').map(s => s.trim());
for (let i = 0; i < attrNames.length; i++) {
if (selectedAttributes[attrNames[i]] !== attrValues[i]) return false;
}
return true;
});
} else {
// Single variant — just use the first variant
matchedVariant = currentProductData.variants && currentProductData.variants.length > 0
? currentProductData.variants[0]
: null;
}
if (!matchedVariant) {
modalError.text('請選擇有效的產品規格');
return;
}
closeModal();
// Do AJAX add to cart following your original logic:
if (!matchedVariant || !matchedVariant.id) {
Swal.fire({
icon: 'error',
title: '錯誤',
text: '無法找到匹配的產品規格,請重試',
});
return;
}
$.ajax({
type: 'POST',
url: base_url + 'cart/manage',
data: {
product_variant_id: matchedVariant.id,
qty: qty,
is_saved_for_later: false,
[csrfName]: csrfHash,
},
dataType: 'json',
success: function (result) {
csrfName = result.csrfName;
csrfHash = result.csrfHash;
if (!result.error) {
Toast.fire({
icon: 'success',
title: result.message
});
$('.cart_count').each(function () {
$(this).text(result.data.cart_count);
});
display_cart(result.data.items);
} else {
if (is_loggedin == 0) {
Toast.fire({
icon: 'success',
title: "已加入至購物車"
});
var cart_item = {
product_variant_id: matchedVariant.id,
name: currentProductData.title || '',
short_description: currentProductData.description || '',
qty: qty,
image: currentProductData.image || '',
price: currentProductData.price
};
var cart = localStorage.getItem("cart");
cart = cart ? JSON.parse(cart) : [];
cart.push(cart_item);
localStorage.setItem("cart", JSON.stringify(cart));
display_cart(cart);
} else {
Toast.fire({
icon: 'error',
title: result.message
});
}
}
},
error: function () {
Toast.fire({
icon: 'error',
title: '伺服器錯誤,請稍後重試'
});
}
});
});
// Bind popup open on all add_to_cart buttons, pass variants JSON as data attribute if possible
(document).on('click', '.add_to_cart', function (e) {
e.preventDefault();
const btn = (this);
// Fetch variants JSON from data-variants attribute (set server side as JSON string)
let variantsData = [];
try {
variantsData = btn.attr('data-variants') ? JSON.parse(btn.attr('data-variants')) : [];
} catch {
variantsData = [];
}
const productData = {
id: btn.data('product-id'),
title: btn.data('product-title'),
name: btn.data('product-title'),
price: btn.data('product-price'),
image: btn.data('product-image'),
min: Number(btn.data('min')) || 1,
step: Number(btn.data('step')) || 1,
max: Number(btn.data('max')) || null,
variants: variantsData,
description: btn.data('product-description') || '',
hasMultipleVariants: btn.data('has-multiple-variants') === 1 || btn.data('has-multiple-variants') === '1',
};
openModal(productData, btn);
});
});
And following CSS:
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.6);
display: flex;
justify-content: center;
align-items: center;
z-index: 1050;
overflow: hidden;
animation: fadeIn 0.3s ease forwards;
}
.modal-window {
background: #fff;
border-radius: 12px;
max-height: 90vh;
max-width: 480px;
width: 90%;
display: flex;
flex-direction: column;
opacity: 0;
transform: translateY(20px);
animation: slideFadeIn 0.3s forwards;
overflow: hidden;
}
.modal-header {
padding: 16px 24px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h2 {
margin: 0;
font-weight: 700;
font-size: 1.25rem;
}
.modal-close {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
line-height: 1;
}
.modal-content {
padding: 24px;
overflow-y: auto;
flex-grow: 1;
}
.quantity-input {
display: flex;
align-items: center;
max-width: 180px;
margin-top: 8px;
}
.qty-btn {
background-color: #e2e8f0;
border: none;
width: 36px;
height: 36px;
font-size: 1.5rem;
cursor: pointer;
border-radius: 50%;
line-height: 1;
user-select: none;
}
.qty-btn:hover {
background-color: #cbd5e1;
}
#modal-qty {
width: 64px;
height: 36px;
text-align: center;
font-size: 1rem;
border: 1px solid #ccc;
margin: 0 8px;
border-radius: 6px;
}
#variants-container {
margin-bottom: 18px;
}
/* Variant option styles */
.variant-group {
margin-bottom: 12px;
}
.variant-label {
display: block;
font-weight: 600;
margin-bottom: 4px;
}
.variant-options {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.variant-option {
border: 1px solid #b0bec5;
border-radius: 8px;
padding: 6px 10px;
cursor: pointer;
user-select: none;
font-size: 0.875rem;
background-color: #f8fafc;
transition: background-color 0.15s ease, border-color 0.15s ease;
}
.variant-option.selected,
.variant-option:hover {
border-color: #3b82f6;
background-color: #dbeafe;
}
.variant-option input[type="radio"] {
display: none;
}
@media (max-width: 767.98px) {
.modal-overlay {
align-items: flex-end;
padding: 8px;
}
.modal-window {
width: 100%;
max-width: unset;
border-radius: 16px 16px 0 0;
max-height: 70vh;
transform: translateY(100%);
animation: slideUpIn 0.3s forwards;
}
}
@keyframes fadeIn {
to {opacity: 1;}
}
@keyframes slideFadeIn {
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideUpIn {
to {
opacity: 1;
transform: translateY(0);
}
}
I want to add the part for display the price info before submit button ("確認加入購物車"), such as discounted unit price, discounted percentage, total price calculated with quantity.
please provide the code for additional part, make sure fulfill the responsive layout for pc, tablet and mobile.