JavaScript Weight Input Validation Popup Triggering Multiple Times

I’m working on a weight tracking application using JavaScript, and I’m encountering an issue where the “Please enter your weight” alert appears when I try to save the weight. It seems like the saveWeight function is being triggered twice, causing the validation to fail the second time.

document.addEventListener(‘DOMContentLoaded’, function() {
const formattedDate = new Date().toISOString().split(‘T’)[0];
document.getElementById(‘currentDate’).textContent = Today's Date: ${formattedDate};

const weightInput = document.getElementById('weightInput');
const heightInput = document.getElementById('heightInput');
const genderSelect = document.getElementById('genderSelect');
const saveButton = document.getElementById('saveButton');
const clearButton = document.getElementById('clearButton');
const poundsOutput = document.getElementById('poundsOutput');
const bmiWeightOutput = document.getElementById('bmiWeight');
const bmiOutput = document.getElementById('bmiOutput');
const bmiStatus = document.getElementById('bmiStatus');
const ctx = document.getElementById('weightChart').getContext('2d');
let weightChart = null;

function loadSavedRecords() {
    const savedWeights = JSON.parse(localStorage.getItem('weightRecords')) || [];
    renderChart(savedWeights);
}

function saveWeight() {
    const weight = parseFloat(weightInput.value);
    
    // Check if the weight is valid before doing anything else
    if (weight) {
        let savedWeights = JSON.parse(localStorage.getItem('weightRecords')) || [];
        const currentDate = new Date().toISOString().split('T')[0]; // Get the current date again
        
        savedWeights.push({ date: currentDate, weight });
        localStorage.setItem('weightRecords', JSON.stringify(savedWeights));
        loadSavedRecords();
        calculateBMI(weight);
        weightInput.value = ''; // Clear the input field after saving
    } else {
        alert('Please enter your weight');
    }
}

function renderChart(savedWeights) {
    const labels = savedWeights.map(record => record.date);
    const data = savedWeights.map(record => record.weight);

    if (weightChart) {
        weightChart.destroy();
    }

    if (data.length > 0) {
        weightChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Weight (kg)',
                    data: data,
                    backgroundColor: 'rgba(75, 192, 192, 0.6)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 2,
                }]
            },
            options: {
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: 'Date'
                        }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Weight (kg)'
                        }
                    }
                }
            }
        });
    } else {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    }
}

function calculateBMI(weight) {
    const heightInMeters = heightInput.value / 100;
    const bmi = (weight / (heightInMeters * heightInMeters)).toFixed(2);
    bmiWeightOutput.textContent = weight;
    bmiOutput.textContent = bmi;

    let status;
    if (bmi < 18.5) status = "Underweight";
    else if (bmi < 24) status = "Normal weight";
    else if (bmi < 29) status = "Overweight";
    else status = "Obesity";

    bmiStatus.textContent = status;
}

function clearData() {
    localStorage.removeItem('weightRecords');
    loadSavedRecords();
    bmiWeightOutput.textContent = '0';
    bmiOutput.textContent = '0';
    bmiStatus.textContent = 'Unknown';
}

const confirmModal = document.getElementById('confirmModal');
const modalClose = document.getElementById('modalClose');
const cancelClear = document.getElementById('cancelClear');
const confirmClear = document.getElementById('confirmClear');

clearButton.addEventListener('click', function() {
    confirmModal.style.display = 'block';
});

modalClose.onclick = function() {
    confirmModal.style.display = 'none';
}

cancelClear.onclick = function() {
    confirmModal.style.display = 'none';
}

confirmClear.onclick = function() {
    clearData();
    confirmModal.style.display = 'none';
}

weightInput.addEventListener('input', function() {
    const weight = parseFloat(weightInput.value);
    if (weight) {
        poundsOutput.textContent = (weight * 2.20462).toFixed(2);
    } else {
        poundsOutput.textContent = '0';
    }
});

saveButton.addEventListener('click', saveWeight);

loadSavedRecords();

});

——————————————-CODE END———————————————-

I have ensured that there are no duplicate event listeners attached to the save button.
The input field for weight is cleared after saving, but I believe the issue might be with how the weight is being parsed or the event listener itself.

Here’s the key part of my code related to saving the weight:

function saveWeight() {
const weight = parseFloat(weightInput.value);

// Check if the weight is valid before doing anything else
if (weight) {
    let savedWeights = JSON.parse(localStorage.getItem('weightRecords')) || [];
    const currentDate = new Date().toISOString().split('T')[0]; // Get the current date again
    
    savedWeights.push({ date: currentDate, weight });
    localStorage.setItem('weightRecords', JSON.stringify(savedWeights));
    loadSavedRecords();
    calculateBMI(weight);
    weightInput.value = ''; // Clear the input field after saving
} else {
    alert('Please enter your weight');
}

}

saveButton.addEventListener(‘click’, saveWeight);

New contributor

Maninder Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật