skip to Main Content

I want to add a autocomplete function to each country so I can start by typing like: "arg " and it would complete it to "argentina"

argentina.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Stories</title>
    <link rel="stylesheet" href="../CSS/usa.css">
</head>
<body>
    <header>
        <h1>Stories</h1>
    </header>
    <main>
        <div id="content-wrapper">
            <div id="get-container">
                <input type="text" id="story-number" placeholder="Enter story number">
                <button id="get" type="button">Get Story</button>
                <button id="getRandom" type="button">Random Story</button>
            </div>
            <div id="story-container">
                <!-- Story content will be displayed here -->
                <div id="generated-text"></div>
                <button id="clear">Clear</button>
            </div>
        </div>
    </main>
    <script src="Scripts/argentina.js"></script>
</body>
</html>

argentina.css

        body {
          font-family: Arial, sans-serif;
          background-color: #f0f0f0;
          margin: 0;
          padding: 0;
        }

        header {
            background-color: #ff6600;
            color: #fff;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            border-radius: 4px;
            margin-bottom: 20px;
            width: 100%;
            padding: 10px 0;
        }

        h1 {
          font-size: 28px;
          margin: 0;
        }

        main {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center; /* Center content vertically on the phone */
          background-color: #fff;
          border-radius: 4px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          padding: 20px;
          margin: 0 auto;
          max-width: 100%; /* Default width */
          overflow-x: hidden;
          max-height: 700px; /* Adjust the height as needed for phones */
          overflow-y: auto; /* Add this line for the vertical scrollbar */
        }

        #content-wrapper {
          padding: 20px;
          max-width: 100%; /* Default width */
          text-align: center;
          margin: 20px;
          overflow-x: hidden;
        }

        #story-number {
          padding: 10px 16px;
          font-size: 14px;
          border: 1px solid #ccc;
          border-radius: 4px;
          width: 200px;
          height: 30px;
          margin-bottom: 10px;
        }

        #get-container {
          display: flex;
          flex-direction: column;
          align-items: center;
        }

        #get,
        #getRandom,
        #clear {
          background-color: #ff6600;
          color: #fff;
          border: none;
          padding: 10px 20px;
          font-size: 16px;
          cursor: pointer;
          border-radius: 4px;
          transition: background-color 0.3s ease;
          margin-bottom: 10px;
          outline: none; /* Remove focus outline */
        }

        #story-container {
          background-color: #fff;
          text-align: center;
          display: none;
        }

        #generated-text {
          font-size: 18px;
          line-height: 1.5;
          margin-bottom: 10px;
          color: #333;
          text-align: center;
        }

        #generated-text span {
          font-weight: bold;
          color: #000;
          font-size: 20px;
        }

        #clear {
          display: block;
          margin: 10px auto;
        }

        @media (max-width: 600px) {
          #get,
          #clear {
            font-size: 10px !important;
            padding: 20px 20px !important;
          }
        }

        /* Media query for screens larger than your phone */
        @media (min-width: 601px) {
          main {
            max-width: 35%; /* Adjust the width for the container on PC */
            max-height: 500px;
          }
        }

argentina.js

document.addEventListener('DOMContentLoaded', function () {
    var totalStories = 1000;
    var currentStory = null;
    var storyContainer = document.getElementById('story-container');
    var contentWrapper = document.getElementById('content-wrapper');
    var storyNumberInput = document.getElementById('story-number');
    var getButton = document.getElementById('get');
    var getRandomButton = document.getElementById('getRandom');
    var clearButton = document.getElementById('clear');

    function clearStoryContainer() {
        if (storyContainer) {
            storyContainer.style.display = 'none';
            var generatedTextElement = document.getElementById('generated-text');
            if (generatedTextElement) {
                generatedTextElement.innerHTML = '';
            }
            if (contentWrapper) {
                contentWrapper.style.marginTop = '0px';
            }
            currentStory = null;
            storyNumberInput.value = ''; // Clear the input text
        }
    }

    function fetchStory(storyNumber) {
        clearStoryContainer();
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'PHP/argentina.php?story=' + storyNumber, true);
        xhr.onload = function () {
            if (xhr.status === 200) {
                if (storyContainer) {
                    storyContainer.style.display = 'block';
                    var generatedText = xhr.responseText;
                    var generatedTextElement = document.getElementById('generated-text');
                    if (generatedTextElement) {
                        generatedTextElement.innerHTML = parseAndStyleTitles(generatedText);
                    } else {
                        console.log('Generated text element not found.');
                    }
                    if (contentWrapper) {
                        contentWrapper.style.marginTop = '0';
                    }
                    currentStory = storyNumber;
                } else {
                    console.log('Story container element not found.');
                }
            } else {
                console.log('Error fetching story. Status code: ' + xhr.status);
                clearStoryContainer();
                if (xhr.status === 404) {
                    displayErrorMessage('Please enter a valid number between 1 and ' + totalStories + '.');
                } else {
                    displayErrorMessage('Error fetching story.');
                }
            }
        };
        xhr.onerror = function () {
            console.log('Network error while fetching story.');
            clearStoryContainer();
            displayErrorMessage('Network error while fetching story.');
        };
        xhr.send();
    }

    function displayErrorMessage(errorMessage) {
        if (storyContainer) {
            storyContainer.style.display = 'block';
        }
        var generatedTextElement = document.getElementById('generated-text');
        if (generatedTextElement) {
            generatedTextElement.innerHTML = errorMessage;
        }
        if (contentWrapper) {
            contentWrapper.style.marginTop = '60px';
        }
        currentStory = null;
    }

    function parseAndStyleTitles(text) {
        return text.replace(/[[(.*?)]]/g, function (match, title) {
            return '<span>' + title + '</span>';
        });
    }

    getButton.addEventListener('click', function () {
        var storyNumber = parseInt(storyNumberInput.value);

        if (!isNaN(storyNumber) && storyNumber >= 1 && storyNumber <= totalStories) {
            fetchStory(storyNumber);
        } else {
            displayErrorMessage('Please enter a valid number between 1 and ' + totalStories + '.');
        }
    });

    getRandomButton.addEventListener('click', function () {
        var randomStoryNumber = Math.floor(Math.random() * totalStories) + 1;
        fetchStory(randomStoryNumber);
    });

    clearButton.addEventListener('click', function () {
        clearStoryContainer();
    });

    storyNumberInput.addEventListener('keyup', function (event) {
        if (event.key === 'Enter') {
            getButton.click();
        }
    });
});

If someone would be able to help me with this I would be very thankful. I’ve been looking at different solutions but haven’t gotten anything to work.

2

Answers


  1. An autocomplete dropdown in HTML is often implemented with a combination of HTML, CSS, and JavaScript. It allows users to type in a text input field, and as they type, a dropdown list of suggestions or options appears. Here’s a basic example of an autocomplete dropdown using HTML, CSS, and JavaScript:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Autocomplete Dropdown Example</title>
        <style>
            /* Style for the autocomplete container */
            .autocomplete {
                position: relative;
                display: inline-block;
            }
    
            /* Style for the input field */
            input[type="text"] {
                width: 200px;
                padding: 5px;
            }
    
            /* Style for the autocomplete dropdown */
            .autocomplete-items {
                position: absolute;
                border: 1px solid #ccc;
                max-height: 150px;
                overflow-y: auto;
            }
    
            /* Style for each autocomplete item */
            .autocomplete-item {
                padding: 5px;
                cursor: pointer;
            }
    
            /* Highlight the selected item */
            .autocomplete-item:hover {
                background-color: #f2f2f2;
            }
        </style>
    </head>
    <body>
        <h1>Autocomplete Dropdown Example</h1>
        <div class="autocomplete">
            <input type="text" id="myInput" placeholder="Type to autocomplete">
            <div class="autocomplete-items" id="autocomplete-list"></div>
        </div>
    
        <script>
            // Sample list of autocomplete options
            var countries = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia"];
    
            // Get references to the input field and the dropdown list
            var input = document.getElementById("myInput");
            var autocompleteList = document.getElementById("autocomplete-list");
    
            // Event listener for input field
            input.addEventListener("input", function() {
                var inputValue = input.value;
                autocompleteList.innerHTML = '';
    
                // Filter and display matching items
                countries.forEach(function(country) {
                    if (country.toLowerCase().indexOf(inputValue.toLowerCase()) !== -1) {
                        var item = document.createElement("div");
                        item.className = "autocomplete-item";
                        item.textContent = country;
                        item.addEventListener("click", function() {
                            input.value = country;
                            autocompleteList.innerHTML = '';
                        });
                        autocompleteList.appendChild(item);
                    }
                });
            });
        </script>
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search