Hi MongoDeBians!
I want to build an autocomplete form in a Django webapp. I have already been able to do the search bar where I query my MongoDB database but how can I add an autocomplete? I tried to adapt an official tutorial that does it with Javascript:
search_similar.html
:
{% extends "todo/base.html" %}
{% block content %}
<div class="recommendations">
<!-- <div class="login-page"> -->
<div class="form">
<form action="{% url 'search_results' %}" method="get">
<input name="q" type="text" placeholder="Perfume name...">
<input id="perfumename" type ="submit" value="Find Similar Perfumes" autocomplete="nope"/>
</form>
<form class="login-form" action = "similar_results/" method="POST">
<input type="text" placeholder="perfume name"/> <!-- https://www.youtube.com/watch?v=TRODv6UTXpM&ab_channel=ProgrammingKnowledge -->
{% csrf_token %}
<input id="perfumename2" type ="submit" value="Find Similar Perfumes" autocomplete="nope"/>
</form>
</div>
<script>
$(document).ready(function() {
$("#perfumename").autocomplete({
source: async function(request, response){
let data=await fetch(`http://localhost:8000/search_similar?q={request.term}`)
.then(results => results.json())
.then(results => results.map(result => {
return { label: result.name, value: result.name, id:result._id };
}
response(data);
},
minLength=2,
select: function(event, ui){
console.log(ui.item);
}
})
}),
$(document).ready(function() {
$("#perfumename2").autocomplete({
source: async function(request, response){
let data=await fetch(`http://localhost:8000/search_similar?q={request.term}`)
.then(results => results.json())
.then(results => results.map(result => {
return { label: result.name, value: result.name, id:result._id };
}
response(data);
},
minLength=2,
select: function(event, ui){
console.log(ui.item);
}
})
})
</script>
</div>
{% endblock %}
Even when I have autocomplete="nope"
the first search bar still shows up the default autocomplete by chrome and doesn’t show up the one I built in MongoDB. The second doesn’t show up anything, even when I link the id to the script.
Do you know how I can handle that?