Disabling an option in a drop down menu

I have a drop down menu with multiple hours, this drop down menu is used for reservations and I want to make it so that an hour thats already reserved to be disabled and greyed out. However, the code makes it so that the hour is invisible and that the next 30 minute intervals are different.

// Fonction pour récupérer le nom du salon par son ID
async function getSalonNameById(salonId) {
    try {
        const response = await fetch(`/salons/${salonId}`);
        if (!response.ok) {
            throw new Error('Erreur lors de la récupération des informations du salon.');
        }
        const salon = await response.json();
        if (salon && typeof salon === 'object') {
            return salon.NomEntreprise;
        } else {
            return null;
        }
    } catch (error) {
        console.error('Erreur:', error);
        return null;
    }
}

document.addEventListener("DOMContentLoaded", async function () {
    var token = sessionStorage.getItem("token");
    var accountType = sessionStorage.getItem("accountType");

    if (token) {
        var button = document.querySelector(".nav-menu .link[href='inscription.html']");
        if (button) {
            if (accountType === "personnel") {
                button.textContent = "Mon Compte";
                button.href = "comptepersonnel.html";
            } else if (accountType === "entreprise") {
                button.textContent = "Mon Salon";
                button.href = "compteentreprise.html";
            }
        }
    }

    const currentUrl = new URL(window.location.href);
    const salonId = currentUrl.searchParams.get("id");

    if (!salonId) {
        console.error("Aucun ID de salon trouvé dans l'URL.");
        return;
    }

    try {
        const response = await fetch(`/salons/${salonId}`);
        if (!response.ok) {
            throw new Error('Erreur lors de la récupération des informations du salon.');
        }
        const salon = await response.json();
        if (salon) {
            updateReservationInfo(salon);
        }
    } catch (error) {
        console.error('Erreur lors de la récupération des informations du salon pour la réservation :', error);
    }

    function updateReservationInfo(salon) {
        const reservationContainer = document.getElementById('reservation-section');

        function generateHoursOptions(openHours, reservedHours) {
            console.log("openHours:", openHours);
            console.log("reservedHours inside generateHoursOptions:", reservedHours);

            if (openHours === "Fermé") {
                return '<option value="" disabled>Aucune heure disponible</option>';
            }

            reservedHours = reservedHours || []; // Ensure reservedHours is an array

            const [opening, closing] = openHours.split(' - ');
            const openingHour = parseInt(opening.split('h')[0], 10);
            const openingMinute = parseInt(opening.split('h')[1], 10);
            const closingHour = parseInt(closing.split('h')[0], 10);
            const closingMinute = parseInt(closing.split('h')[1], 10);

            const availableHours = [];
            let currentHour = openingHour;
            let currentMinute = openingMinute;

            while (currentHour < closingHour || (currentHour === closingHour && currentMinute < closingMinute)) {
                const formattedHour = `${currentHour < 10 ? '0' : ''}${currentHour}:${currentMinute < 10 ? '0' : ''}${currentMinute}`;
                if (!reservedHours.includes(formattedHour)) {
                    availableHours.push(`<option value="${formattedHour}">${formattedHour}</option>`);
                }
                currentMinute += 30;
                if (currentMinute >= 60) {
                    currentMinute = 0;
                    currentHour++;
                }
            }

            return availableHours.length > 0 ? availableHours.join('') : '<option value="" disabled>Aucune heure disponible</option>';
        }

        reservationContainer.innerHTML = `
            <h1>Réservation</h1><br/>
            <h2>${salon.NomEntreprise}</h2>
            <p>Téléphone: ${salon.NumeroTelephone}</p>
            <p>Adresse: ${salon.Adresse}</p><br/>
            <form id="reservationForm">
                <label for="services">Choisir des services:</label>
                <div id="services" name="services">
                    ${salon.ServiceOffert.split(';').map(service => `
                        <label>
                            <input type="checkbox" name="service" value="${service.trim()}"> ${service.trim()}
                        </label>
                    `).join('')}
                </div>
                <label for="date">Choisir une date :</label>
                <input type="date" id="date" name="date" required>
                <label for="heure">Choisir une heure :</label>
                <select id="heure" name="heure" required>
                    <option value="" disabled selected>Choisir une heure</option>
                </select>
                <p id="closedMessage" class="closed-message" style="display: none;">Ce salon est fermé ce jour-là.</p>
                <br><br>
                <button type="button" id="confirmer">Confirmer la réservation</button>
                <button type="button" id="annuler">Annuler</button>
            </form>
        `;

        const dateInput = document.getElementById('date');
        const today = new Date().toISOString().split('T')[0];
        dateInput.setAttribute('min', today);

        dateInput.addEventListener('change', async function () {
            const selectedDate = this.value;
            const selectedDayIndex = new Date(selectedDate).getDay();
            const daysOfWeek = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];
            const selectedDay = daysOfWeek[selectedDayIndex];
            const openHoursForSelectedDay = salon[selectedDay];

            const heureSelect = document.getElementById('heure');
            const closedMessage = document.getElementById('closedMessage');

            if (openHoursForSelectedDay === "Fermé") {
                heureSelect.innerHTML = '<option value="" disabled selected>Choisir une heure</option>';
                heureSelect.disabled = true;
                closedMessage.style.display = 'block';
            } else {
                try {
                    const reservedHours = await fetchReservedHours(salonId, selectedDate);
                    console.log("reservedHours fetched:", reservedHours);
                    if (!Array.isArray(reservedHours)) {
                        console.error("reservedHours is not an array:", reservedHours);
                    }
                    heureSelect.innerHTML = generateHoursOptions(openHoursForSelectedDay, reservedHours);
                    heureSelect.disabled = false;
                    closedMessage.style.display = 'none';
                } catch (error) {
                    console.error('Erreur lors de la récupération des heures réservées :', error);
                }
            }
        });

        const confirmerBtn = document.getElementById('confirmer');
        if (confirmerBtn) {
            confirmerBtn.addEventListener('click', async function () {
                const selectedServices = Array.from(document.querySelectorAll('input[name="service"]:checked')).map(checkbox => checkbox.value);
                const date = document.getElementById('date').value;
                const heure = document.getElementById('heure').value;

                if (selectedServices.length === 0) {
                    alert('Veuillez sélectionner au moins un service.');
                    return;
                }

                try {
                    const nomSalon = await getSalonNameById(salonId);

                    const response = await fetch('/reservation', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            salonId: salonId,
                            service: selectedServices.join(';'),
                            date: date,
                            heure: heure,
                            token: token,
                            nomSalon: nomSalon
                        }),
                    });

                    if (response.ok) {
                        window.location.href = 'comptepersonnel.html?tab=reservation';
                    } else {
                        throw new Error('La réservation a échoué.');
                    }
                } catch (error) {
                    console.error('Erreur lors de la réservation :', error);
                }
            });
        }

        const annulerBtn = document.getElementById('annuler');
        if (annulerBtn) {
            annulerBtn.addEventListener('click', function () {
                window.location.href = 'Salons.html';
            });
        }
    }

    async function fetchReservedHours(salonId, date) {
        try {
            const response = await fetch(`/reservations/${salonId}/${date}`);
            if (!response.ok) {
                throw new Error('Erreur lors de la récupération des heures réservées.');
            }
            const reservedHours = await response.json();
            console.log("Reserved hours response:", reservedHours);
            return reservedHours.map(reservation => reservation.heure);
        } catch (error) {
            console.error('Erreur lors de la récupération des heures réservées :', error);
            return [];
        }
    }
});

For those curious, here is some console log:

Just some logs to see how fetched reserved hours are handled

I tried to revise my code to make it so that option just disappeared but then the intervals changed.

So when i tried to go back to making it disabled, the option would be there and not disabled.

I`ve tried searching for codes online but nothing worked for my specific code. I’m at a loss.

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