← Back to notes

Populate the Dropdown Menu with Painting Titles

Populate the Dropdown Menu with Painting Titles.md

Populate the Dropdown Menu with Painting Titles

To populate the dropdown menu with painting titles dynamically using the data fetched from your /painting-titles endpoint, you need to adjust your JavaScript to fetch the titles and then update the dropdown options accordingly. Here’s a suggested approach:

HTML

Your HTML structure looks good. Make sure the select element has an ID that you can easily reference in your JavaScript, like painting-title-selector as you’ve used.

JavaScript

You’ll need to write JavaScript that:

  1. Fetches the painting titles from your /painting-titles endpoint.
  2. Clears existing options in the dropdown.
  3. Loops through the fetched titles and creates a new option element for each title, which is then appended to the dropdown.

Here’s an example:

// Fetch painting titles and populate the dropdown
function fetchPaintingTitles() {
    fetch('/painting-titles')
        .then(response => response.json())
        .then(titles => {
            const dropdown = document.getElementById('painting-title-selector');
            dropdown.innerHTML = '';  // Clear existing options
            titles.forEach(titleObj => {
                const option = new Option(titleObj.painting_title, titleObj.painting_title);  // Assuming 'painting_title' is the key in your response
                dropdown.add(option);
            });
        })
        .catch(error => console.error('Error fetching painting titles:', error));
}

// Call fetchPaintingTitles on page load or when appropriate
document.addEventListener('DOMContentLoaded', fetchPaintingTitles);

// Optional: Fetch details for the selected painting when the button is clicked
document.getElementById('fetchSelecedPainting').addEventListener('click', () => {
    const selectedTitle = document.getElementById('painting-title-selector').value;
    // Implement the logic to fetch and display details for the selected painting
    // This might involve another fetch request to an endpoint like '/painting-details/:title'
});

Adjustments in app.js

Your app.get('/painting-titles', ...) endpoint in app.js looks correctly set up to serve the painting titles. No changes are needed here based on the provided JavaScript.

Summary

This approach should dynamically populate your dropdown with painting titles from your database and provide a foundation for fetching and displaying detailed information about the selected painting.