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
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.
<!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>
.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;
}
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
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));
?>
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.