Creating an Auto-Complete Input with Suggestions Using HTML, CSS, JS, PHP

Answered using ChatGPT 4o by ChatGPT4o

Question:

An Auto-Complete Input, with Suggestion Div (above of input section); Suggest Tags Based of Input Word, for an Array like this: 'a' => {a1, word1, tag1} 'word1' => {sample1, sample2} HTML5, CSS, JS, AJAX. Receive array suggestion via Ajax from PHP

Answer:

Creating an auto-complete input with a suggestion div that appears above the input section involves several steps. Below is a complete example using HTML5, CSS, JavaScript, and AJAX to fetch suggestions from a PHP backend.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Auto-Complete Input</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="autocomplete-container">
        <div id="suggestions" class="suggestions"></div>
        <input type="text" id="autocomplete-input" placeholder="Start typing...">
    </div>

    <script src="script.js"></script>
</body>
</html>

CSS (styles.css)

.autocomplete-container {
    position: relative;
    width: 300px;
    margin: 50px auto;
}

#autocomplete-input {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
}

.suggestions {
    position: absolute;
    top: -100px; /* Adjust this value to position the suggestions above the input */
    width: 100%;
    border: 1px solid #ccc;
    background-color: #fff;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.suggestion-item {
    padding: 10px;
    cursor: pointer;
}

.suggestion-item:hover {
    background-color: #f0f0f0;
}

JavaScript (script.js)

document.addEventListener('DOMContentLoaded', function() {
    const input = document.getElementById('autocomplete-input');
    const suggestionsDiv = document.getElementById('suggestions');

    input.addEventListener('input', function() {
        const query = input.value;
        if (query.length > 0) {
            fetchSuggestions(query);
        } else {
            suggestionsDiv.innerHTML = '';
        }
    });

    function fetchSuggestions(query) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `suggestions.php?query=${query}`, true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                const suggestions = JSON.parse(xhr.responseText);
                displaySuggestions(suggestions);
            }
        };
        xhr.send();
    }

    function displaySuggestions(suggestions) {
        suggestionsDiv.innerHTML = '';
        suggestions.forEach(suggestion => {
            const div = document.createElement('div');
            div.classList.add('suggestion-item');
            div.textContent = suggestion;
            div.addEventListener('click', function() {
                input.value = suggestion;
                suggestionsDiv.innerHTML = '';
            });
            suggestionsDiv.appendChild(div);
        });
    }
});

PHP (suggestions.php)

<?php
header('Content-Type: application/json');

$suggestions = [
    'a' => ['a1', 'word1', 'tag1'],
    'word1' => ['sample1', 'sample2']
];

$query = $_GET['query'];
$result = [];

foreach ($suggestions as $key => $values) {
    if (strpos($key, $query) !== false) {
        $result = array_merge($result, $values);
    }
}

echo json_encode(array_unique($result));
?>

Explanation

  1. HTML: The HTML structure includes an input field and a div for displaying suggestions.
  2. CSS: The CSS styles the input field and the suggestions div, positioning the suggestions above the input field.
  3. JavaScript: The JavaScript listens for input events, fetches suggestions via AJAX, and displays them in the suggestions div. Clicking a suggestion fills the input field with the selected suggestion.
  4. PHP: The PHP script receives the query, searches for matching keys in the suggestions array, and returns the corresponding values as a JSON response.

This setup should provide a functional auto-complete input with suggestions appearing above the input field. Adjust the CSS as needed to fit your design requirements.