Hi to all,
I am new there. I am looking for help for an autocompletion script .
I tried to code it but ... it doesn't work š¢
Here are my codes
A simple HTML input with an ID
My Ajax / Jquery code
Thanks for your precious possible help
Ludo
I am new there. I am looking for help for an autocompletion script .
I tried to code it but ... it doesn't work š¢
Here are my codes
A simple HTML input with an ID
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Autocompletion </title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<label for="search">Search:</label>
<input type="text" id="search" name="search" autocomplete="off">
<div id="search-results"></div>
<script src="script.js"></script>
</body>
</html>
My Ajax / Jquery code
JavaScript:
$(document).ready(function() {
$('#search').on('input', function() {
var query = $(this).val();
// I check if the input is not empty
if (query.length > 0) {
// Ajax request to JSONPlaceholder API
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos',
type: 'GET',
data: { title: query },
success: function(data) {
// Display the results in the #search-results div
displayResults(data);
}
});
} else {
// Clear the #search-results div if the input is empty
$('#search-results').empty();
}
});
function displayResults(results) {
// Display the results
$('#search-results').empty();
results.forEach(function(result) {
$('#search-results').append('<div>' + result.title + '</div>');
});
}
});
Thanks for your precious possible help
Ludo