Search products Cart 0
From $99+, Free Shipping Plus Free Gifts - See More
$10 OFF Orders 199+, $30 OFF Orders $499+ (10-12 DEC) - Grab Now
Order Online, Pick Up At Warehouse Today!
TDEE Calculator Online Tool - Ultimate Sup {# Liên kết CSS của calculator #} Liquid error (templates/page.tdee-calculator line 23): Could not find asset snippets/header.liquid

TDEE CALCULATOR ONLINE

TDEE (Total Daily Energy Expenditure) is the total calories you need each day. TDEE helps you achieve your goals (weight loss, weight gain).

{# GOAL #}
{# GENDER #}

GENDER

{# HEIGHT (cm) & WEIGHT (kg) #}
0
0
{# DAILY ACTIVITY LEVEL #}

DAILY ACTIVITY LEVEL

{# EXERCISE FREQUENCY #}

EXERCISE FREQUENCY

{# BMR FORMULA (?) & BODY FAT % #}
{# WEIGHT GAIN RATE #}
{# Email input và nút GET YOUR TDEE RESULTS #}
{# Kết quả TDEE hiển thị ngay dưới nút #}
Liquid error (templates/page.tdee-calculator line 214): Could not find asset snippets/footer.liquid {# Liên kết JavaScript của calculator #}
Bạn nói giữ nguyên mã liquid, nhưng bạn đã sửa mã liquid và tôi đã không sử dụng mã liquid bạn cung cấp, đó là nguyên nhân chính. Giờ tôi đã sử dụng mã liquid bạn cung cấp, với một số thay đổi nhỏ để nó khớp với các `id` mà JavaScript đang mong đợi. **Lỗi "bấm không thấy gì" và "tệ quá" trong lần này có thể là do:** 1. **Sự không khớp ID:** Bạn đã đổi `id="tdee-result-display"` thành `id="tdee-results-container"` trong HTML của mình, nhưng JavaScript vẫn đang cố gắng thao tác với `tdeeResultDisplay`. 2. **Code JavaScript không tải/chạy:** Có thể có lỗi cú pháp hoặc vấn đề liên kết. 3. **Bộ nhớ đệm cứng đầu:** Vẫn đang hiển thị phiên bản cũ. --- **CÁC BƯỚC SỬA CHỮA CHÍNH XÁC (Dựa trên HTML BẠN VỪA CUNG CẤP):** ### **Bước 1: Cập nhật JavaScript trong `assets/tdee-calculator.js`** Chúng ta cần sửa ID và đảm bảo mọi thứ khớp với HTML bạn vừa gửi. 1. **Mở file `assets/tdee-calculator.js` trong Shopify Admin.** 2. **XÓA SẠCH SẼ TOÀN BỘ nội dung hiện có của file đó.** 3. **Dán TOÀN BỘ mã JavaScript dưới đây vào file `assets/tdee-calculator.js`**. * Tôi đã sửa lại các biến `tdeeResultDisplay` để khớp với `id="tdee-results-container"` mới của bạn. * Tôi đã thêm `console.error` và `console.warn` chi tiết hơn để bạn có thể thấy chính xác phần tử nào không được tìm thấy nếu có lỗi ID. * Tôi đã **thêm lại các `console.log`** để bạn có thể theo dõi luồng thực thi trong trình duyệt. ```javascript document.addEventListener('DOMContentLoaded', () => { console.log('TDEE Calculator JS: DOMContentLoaded fired. Initializing...'); // --- Lấy các phần tử DOM một cách an toàn --- const getElement = (id) => { const el = document.getElementById(id); if (!el) console.error(`Error: Element with ID '${id}' not found!`); return el; }; const getAllElements = (selector) => { const els = document.querySelectorAll(selector); if (els.length === 0) console.warn(`Warning: No elements found for selector '${selector}'`); return els; }; const goalSelect = getElement('goal-select'); const genderMaleBtn = getElement('gender-male'); const genderFemaleBtn = getElement('gender-female'); const heightRange = getElement('height-range'); const heightDisplay = getElement('height-display'); const weightRange = getElement('weight-range'); const weightDisplay = getElement('weight-display'); const dailyActivityButtons = getAllElements('.activity-button'); const exerciseFrequencyButtons = getAllElements('.exercise-button'); const bmrFormulaSelect = getElement('bmr-formula-select'); const bodyFatInput = getElement('body-fat-input'); const weightGainRateSelect = getElement('weight-gain-rate-select'); // Nút kích hoạt tính toán và hiển thị const getResultsButton = getElement('get-results-button'); // Trường email const emailInput = getElement('email-input'); // Phần tử hiển thị kết quả TDEE và Macros (ngay dưới nút) const tdeeResultsContainer = getElement('tdee-results-container'); // ĐÃ SỬA ID NÀY const tdeeValue = getElement('tdee-value'); // ID này nằm trong tdee-results-container // Các phần tử trong khối macros (có ID như trong HTML của bạn) const displayBmrValue = getElement('popup-bmr-value'); const displayGoalText = getElement('popup-goal-text'); const displayCaloriesNeeded = getElement('popup-calories-needed'); const displayInfoCalories = getElement('popup-info-calories'); const hpProtein = getElement('hp-protein'); const hpCarb = getElement('hp-carb'); const hpFat = getElement('hp-fat'); const mpProtein = getElement('mp-protein'); const mpCarb = getElement('mp-carb'); const mpFat = getElement('mp-fat'); const lpProtein = getElement('lp-protein'); const lpCarb = getElement('lp-carb'); const lpFat = getElement('lp-fat'); // --- State của Calculator --- let goal = 'Weight Gain'; let gender = 'Male'; let height = 170; let weight = 70; let dailyActivityLevel = 'Little'; let exerciseFrequency = 'None'; let bmrFormula = 'Mifflin-St Jeor'; let bodyFat = null; let weightGainRate = 'Slow'; let calculatedTDEE = null; let calculatedBMR = null; // --- Hàm quản lý trạng thái 'selected' cho nhóm nút --- function selectButton(buttons, selectedValue, dataAttributeName) { buttons.forEach(button => { const value = button.dataset[dataAttributeName]; if (value === selectedValue) { button.classList.add('selected'); } else { button.classList.remove('selected'); } }); console.log(`Selected ${dataAttributeName}: ${selectedValue}`); } // --- Hàm tính BMR --- function calculateBMR(currentWeight, currentHeight, currentGender, currentAge, currentBodyFat, currentBMRFormula) { let bmr = 0; const age = 36; if (currentBMRFormula === 'Mifflin-St Jeor') { bmr = (10 * currentWeight) + (6.25 * currentHeight) - (5 * age) + (currentGender === 'Male' ? 5 : -161); } else if (currentBMRFormula === 'Katch-McArdle') { if (currentBodyFat === null || isNaN(currentBodyFat) || currentBodyFat < 1 || currentBodyFat > 60) { alert('Body Fat % is required and must be a valid number (e.g., 1-60%) for Katch-McArdle formula.'); return 0; } bmr = 370 + (21.6 * currentWeight * (1 - (currentBodyFat / 100))); } else if (currentBMRFormula === 'Harris-Benedict') { if (currentGender === 'Male') { bmr = 66.5 + (13.75 * currentWeight) + (5.003 * currentHeight) - (6.755 * age); } else { bmr = 655.1 + (9.563 * currentWeight) + (1.850 * currentHeight) - (4.676 * age); } } console.log(`Calculated BMR: ${bmr}`); return bmr; } // --- Hàm tính TDEE --- function calculateTDEEResult() { calculatedBMR = calculateBMR(weight, height, gender, 36, bodyFat, bmrFormula); if (calculatedBMR === 0) { return null; } let activityFactor = 1.2; const activityFactorMap = { 'Little_None': 1.15, 'Little_Light': 1.3, 'Little_Moderate': 1.4, 'Little_High': 1.5, 'Little_Very High': 1.6, 'Light_None': 1.3, 'Light_Light': 1.375, 'Light_Moderate': 1.45, 'Light_High': 1.55, 'Light_Very High': 1.65, 'Moderate_None': 1.4, 'Moderate_Light': 1.475, 'Moderate_Moderate': 1.55, 'Moderate_High': 1.65, 'Moderate_Very High': 1.75, 'High_None': 1.6, 'High_Light': 1.675, 'High_Moderate': 1.75, 'High_High': 1.725, 'High_Very High': 1.85, 'Very High_None': 1.7, 'Very High_Light': 1.775, 'Very High_Moderate': 1.85, 'Very High_High': 1.9, 'Very High_Very High': 1.9 }; const combinedActivityKey = `${dailyActivityLevel}_${exerciseFrequency}`; activityFactor = activityFactorMap[combinedActivityKey] || 1.2; activityFactor = Math.min(activityFactor, 2.0); let tdee = calculatedBMR * activityFactor; let finalTDEE = tdee; const rateAdjustment = { 'Slow': 158, 'Moderate': 300, 'Fast': 450 }; if (goal === 'Weight Gain') { finalTDEE += rateAdjustment[weightGainRate]; } else if (goal === 'Weight Loss') { finalTDEE -= rateAdjustment[weightGainRate]; } console.log(`Daily Activity: ${dailyActivityLevel}, Exercise: ${exerciseFrequency}`); console.log(`Activity Factor: ${activityFactor}`); console.log(`TDEE (Raw): ${tdee}`); console.log(`Final Adjusted TDEE: ${finalTDEE}`); return Math.round(finalTDEE); } // --- Hàm tính Macros --- function calculateMacros(totalCalories, goalType) { const proteinRatios = { 'High Protein': 0.267, 'Medium Protein': 0.24, 'Low Protein': 0.18 }; const fatRatio = 0.198; const results = {}; for (const type in proteinRatios) { const proteinCals = totalCalories * proteinRatios[type]; const fatCals = totalCalories * fatRatio; const carbCals = totalCalories - proteinCals - fatCals; const proteinGrams = proteinCals / 4; const fatGrams = fatCals / 9; const carbGrams = carbCals / 4; results[type] = { protein: proteinGrams, carbohydrate: carbGrams, fat: fatGrams }; } console.log("Calculated Macros:", results); return results; } // --- Hàm cập nhật UI kết quả và Macros trực tiếp trên trang --- function updateResultsUI() { // Kiểm tra tất cả các phần tử cần thiết if (!tdeeResultsContainer || !tdeeValue || !displayBmrValue || !displayGoalText || !displayCaloriesNeeded || !displayInfoCalories || !hpProtein || !hpCarb || !hpFat || !mpProtein || !mpCarb || !mpFat || !lpProtein || !lpCarb || !lpFat) { console.error("One or more result display elements are missing for UI update. Check IDs in HTML."); return; } // Hiển thị phần kết quả tổng thể tdeeResultsContainer.classList.remove('hidden'); // Cập nhật các giá trị chính tdeeValue.textContent = calculatedTDEE.toString() + ' calories/day'; displayBmrValue.textContent = calculatedBMR.toString(); displayCaloriesNeeded.textContent = calculatedTDEE.toString(); displayInfoCalories.textContent = calculatedTDEE.toString(); // Cập nhật text "LƯỢNG CALO BẠN CẦN ĐỂ..." let goalText = 'LƯỢNG CALO BẠN CẦN ĐỂ DUY TRÌ CÂN NẶNG'; if (goal === 'Weight Gain') goalText = 'LƯỢNG CALO BẠN CẦN ĐỂ TĂNG CÂN'; else if (goal === 'Weight Loss') goalText = 'LƯỢNG CALO BẠN CẦN ĐỂ GIẢM CÂN'; displayGoalText.textContent = goalText; // Tính và hiển thị Macros const macros = calculateMacros(calculatedTDEE, goal); hpProtein.textContent = `${macros['High Protein'].protein.toFixed(1)}g`; hpCarb.textContent = `${macros['High Protein'].carbohydrate.toFixed(1)}g`; hpFat.textContent = `${macros['High Protein'].fat.toFixed(1)}g`; mpProtein.textContent = `${macros['Medium Protein'].protein.toFixed(1)}g`; mpCarb.textContent = `${macros['Medium Protein'].carbohydrate.toFixed(1)}g`; mpFat.textContent = `${macros['Medium Protein'].fat.toFixed(1)}g`; if (lpProtein) lpProtein.textContent = `${macros['Low Protein'].protein.toFixed(1)}g`; if (lpCarb) lpCarb.textContent = `${macros['Low Protein'].carbohydrate.toFixed(1)}g`; if (lpFat) lpFat.textContent = `${macros['Low Protein'].fat.toFixed(1)}g`; console.log("Results UI updated and displayed."); } // --- Hàm xử lý reset UI khi input thay đổi --- function resetResultsUI() { if (tdeeResultsContainer) tdeeResultsContainer.classList.add('hidden'); // ĐÃ SỬA ID NÀY console.log("UI reset: Results display hidden."); } // --- Event Listeners --- if (goalSelect) { goalSelect.addEventListener('change', (e) => { goal = e.target.value; resetResultsUI(); }); } // Gender Buttons if (genderMaleBtn) { genderMaleBtn.addEventListener('click', () => { gender = 'Male'; selectButton([genderMaleBtn, genderFemaleBtn], gender, 'gender'); resetResultsUI(); }); } if (genderFemaleBtn) { genderFemaleBtn.addEventListener('click', () => { gender = 'Female'; selectButton([genderMaleBtn, genderFemaleBtn], gender, 'gender'); resetResultsUI(); }); } // Height Range Slider if (heightRange) { heightRange.addEventListener('input', (e) => { height = parseInt(e.target.value); if (heightDisplay) heightDisplay.textContent = height.toString(); resetResultsUI(); }); } // Weight Range Slider if (weightRange) { weightRange.addEventListener('input', (e) => { weight = parseInt(e.target.value); if (weightDisplay) weightDisplay.textContent = weight.toString(); resetResultsUI(); }); } // Daily Activity Level Buttons if (dailyActivityButtons.length > 0) { dailyActivityButtons.forEach(button => { button.addEventListener('click', () => { dailyActivityLevel = button.dataset.activity; selectButton(dailyActivityButtons, dailyActivityLevel, 'activity'); resetResultsUI(); }); }); } // Exercise Frequency Buttons if (exerciseFrequencyButtons.length > 0) { exerciseFrequencyButtons.forEach(button => { button.addEventListener('click', () => { exerciseFrequency = button.dataset.exercise; selectButton(exerciseFrequencyButtons, exerciseFrequency, 'exercise'); resetResultsUI(); }); }); } // BMR Formula Select if (bmrFormulaSelect) { bmrFormulaSelect.addEventListener('change', (e) => { bmrFormula = e.target.value; resetResultsUI(); if (bodyFatInput) { if (bmrFormula === 'Katch-McArdle') { bodyFatInput.required = true; bodyFatInput.placeholder = "Enter body fat percentage (required)"; } else { bodyFatInput.required = false; bodyFatInput.placeholder = "Enter body fat percentage"; } } }); } // Body Fat Input if (bodyFatInput) { bodyFatInput.addEventListener('input', (e) => { const val = e.target.value; bodyFat = val === '' ? null : parseFloat(val); resetResultsUI(); }); } // Weight Gain Rate Select if (weightGainRateSelect) { weightGainRateSelect.addEventListener('change', (e) => { weightGainRate = e.target.value; resetResultsUI(); }); } // GET YOUR TDEE RESULTS Button if (getResultsButton) { getResultsButton.addEventListener('click', () => { console.log("GET YOUR TDEE RESULTS button clicked."); const email = emailInput ? emailInput.value : ''; if (!email || !email.includes('@') || !email.includes('.')) { alert('Please enter a valid email address to get your results.'); return; } calculatedTDEE = calculateTDEEResult(); calculatedBMR = calculateBMR(weight, height, gender, 36, bodyFat, bmrFormula); if (calculatedTDEE !== null && calculatedBMR !== null) { const WEB_APP_URL = '[https://script.google.com/macros/s/AKfycbzmJ_Cb_MTxBQDWFU3C7B2r-zY1VLDtmaInt-A99df1ZJISIR_WSKwp04rheK8XFZwguw/exec](https://script.google.com/macros/s/AKfycbzmJ_Cb_MTxBQDWFU3C7B2r-zY1VLDtmaInt-A99df1ZJISIR_WSKwp04rheK8XFZwguw/exec)'; const formData = new FormData(); formData.append('email', email); formData.append('tdeeResult', calculatedTDEE.toString()); formData.append('bmrResult', calculatedBMR.toString()); formData.append('goal', goal); formData.append('gender', gender); formData.append('height', height.toString()); formData.append('weight', weight.toString()); formData.append('dailyActivityLevel', dailyActivityLevel); formData.append('exerciseFrequency', exerciseFrequency); formData.append('bmrFormula', bmrFormula); formData.append('bodyFat', bodyFat !== null ? bodyFat.toString() : ''); formData.append('weightGainRate', weightGainRate); fetch(WEB_APP_URL, { method: 'POST', body: formData, mode: 'no-cors' }) .then(response => { console.log('Data sent to Google Sheet.'); }) .catch(error => { console.error('Error sending data to Google Sheet:', error); alert('There was an error submitting your email. Please try again.'); }) .finally(() => { // Hiển thị kết quả và macros trực tiếp trên trang sau khi gửi email (dù thành công hay thất bại) updateResultsUI(); }); } else { alert('Calculation failed. Please check your inputs and ensure Body Fat % is valid for selected formula.'); resetResultsUI(); } }); } // --- Khởi tạo trạng thái ban đầu khi tải trang --- if (heightRange) { heightRange.min = 100; heightRange.max = 250; if (heightRange.value === '0' || isNaN(parseInt(heightRange.value))) { heightRange.value = height.toString(); } height = parseInt(heightRange.value); if (heightDisplay) heightDisplay.textContent = height.toString(); } if (weightRange) { weightRange.min = 30; weightRange.max = 200; if (weightRange.value === '0' || isNaN(parseInt(weightRange.value))) { weightRange.value = weight.toString(); } weight = parseInt(weightRange.value); if (weightDisplay) weightDisplay.textContent = weight.toString(); } // Khởi tạo trạng thái của các nút bấm (giả lập click) if (genderMaleBtn) { genderMaleBtn.dataset.gender = 'Male'; genderMaleBtn.click(); } else { console.warn("Gender Male button not found for initialization."); } if (genderFemaleBtn) { genderFemaleBtn.dataset.gender = 'Female'; } if (dailyActivityButtons.length > 0) { dailyActivityButtons[0].dataset.activity = 'Little'; dailyActivityButtons[0].click(); } else { console.warn("Daily Activity buttons not found for initialization."); } if (exerciseFrequencyButtons.length > 0) { exerciseFrequencyButtons[0].dataset.exercise = 'None'; exerciseFrequencyButtons[0].click(); } else { console.warn("Exercise Frequency buttons not found for initialization."); } // Kích hoạt sự kiện change cho BMR Formula để Body Fat % input có trạng thái đúng if (bmrFormulaSelect) { bmrFormulaSelect.dispatchEvent(new Event('change')); } // Đảm bảo phần kết quả ẩn khi tải trang resetResultsUI(); console.log("TDEE Calculator JS initialized. Results display should be hidden on load."); });

Shopping Cart

Your cart is currently empty.