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);