I wrote a website for users to change wifi passwords.
Data is stored indata/data.json. This includes room number, AP name, and password.
[ {"Room": "room 1", "AP name": "ap 1", "password": "12345678"}, {"Room": "room 2", "AP name": "ap 2", "password": "12345678"} ]
There is a drop down menu for users to select their room. Dropdown options are generated by JavaScript by getting data from a JSON file. But now no options are showing in the drop down list.
Select your room:
document.addEventListener('DOMContentLoaded', loadRoomNumbers); // Function to load room numbers from data.json function loadRoomNumbers() { const roomSelect = document.getElementById('room'); fetch('data/data.json') .then(response => { if (!response.ok) { throw new Error('Could not load data.json'); } return response.json(); }) .then(roomsData => { roomsData.forEach(roomData => { const option = document.createElement('option'); option.value = roomData.Room; option.textContent = roomData.Room; roomSelect.appendChild(option); }); }) .catch(error => { console.error('Error fetching room data:', error); }); }
May I know which part is incorrect and how to fix it? Thanks
Frankly, your code is quite confusing. For example: you register event listeners for
DOMContentLoadedtwice (at the top and bottom of the code), and they both executeloadRoomNumbers.Let me rewrite your
loadRoomNumbersmethod correctly:document.addEventListener('DOMContentLoaded', loadRoomNumbers); // Function to load room numbers from data.json async function loadRoomNumbers() { const roomSelect = document.getElementById('room'); try { const response = await fetch('data/data.json') if (!response.ok) { throw `Response not ok (${response.status})` } const rooms = await response.json() rooms.forEach(roomData => { const option = document.createElement('option'); option.value = roomData.Room; option.textContent = roomData.Room; roomSelect.appendChild(option); }); } catch (error) { console.error('Error fetching room data:', error); } }Or in a working example:
document.addEventListener('DOMContentLoaded', loadRoomNumbers); // Function to load room numbers from data.json async function loadRoomNumbers() { const roomSelect = document.getElementById('room'); try { // This has to be replaced by fetch('data/data.json') of course const rooms = await [ {"Room": "room 1","AP name": "ap 1","password": "12345678"}, {"Room": "room 2","AP name": "ap 2","password": "12345678"} ] rooms.forEach(roomData => { const option = document.createElement('option'); option.value = roomData.Room; option.textContent = roomData.Room; roomSelect.appendChild(option); }); } catch (error) { console.error('Error fetching room data:', error); } }