I wrote a website for users to change wifi passwords.
Data is stored in data/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.
<tr> <td>Select your room:</td> <td> <select id="room" name="room" required> <option value="" selected>Select room</option> <!-- Room options will be populated by JavaScript --> </select> </td> </tr>
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
DOMContentLoaded
twice (at the top and bottom of the code), and they both executeloadRoomNumbers
.Let me rewrite your
loadRoomNumbers
method correctly:Or in a working example: