anishtulsyan22
New Coder
Hi All,
When I enter text in the search bar , autocomplete feature shows all the related product as expected, But when I remove the text from the input bar and make the text length to 0, it still retains the autocomplete box. Please help me with the related issue. My code is as follows:
When I enter text in the search bar , autocomplete feature shows all the related product as expected, But when I remove the text from the input bar and make the text length to 0, it still retains the autocomplete box. Please help me with the related issue. My code is as follows:
JavaScript:
const compare_search_url = window.location.href
const search_wrapper = document.querySelector(".search_input");
const compare_search_first_form = document.getElementById('compare_search_first_form')
const inputBox = document.getElementById("first_search_input");
const suggbox = document.getElementById("first_autocomplete_box");
const compare_search_first_csrf = document.getElementsByName('csrfmiddlewaretoken')[0].value
inputBox.onkeyup = (e)=>{
send_first_product_compare_data(e.target.value)
}
const send_first_product_compare_data = (first_product_search) => {
$.ajax({
type: 'POST',
url: 'first_product_compare_search/',
data: {
'csrfmiddlewaretoken': compare_search_first_csrf,
'first_product_search': first_product_search,
},
success: (res) => {
first_product_result = res.first_product_result;
if (Array.isArray(first_product_result)) {
product_result = res.first_product_result
if (Array.isArray(product_result)) {
product_result = product_result.map((data)=>{
return data = '<li>' + data.brand + ' ' + data.model_name + '</li>';
});
search_wrapper.classList.add("active");
showSuggestions(product_result);
}
else {
// console.log("Anish");
if (inputBox.value.length > 0) {
suggbox.innerHTML = product_result
console.log("Anish");
} else {
search_wrapper.classList.remove('active')
}
}
// autocomplete(document.getElementById("search_product"), data);
// console.log(first_product_result);
}
// if(res){
// product_result = res.first_product_result
// product_result = product_result.map((data)=>{
// return data = '<li>' + data.brand + ' ' + data.model_name + '</li>';
// });
// search_wrapper.classList.add("active");
// showSuggestions(product_result);
// if(inputBox.value.length == 0){
// console.log("Anish");
// }
// }
},
error: (err) => {
console.log(err)
}
})
}
function showSuggestions(list){
let listData;
if(!list.length){
userValue = inputBox.value;
listData = '<li>' + userValue + '</li>';
}else{
listData = list.join('');
}
suggbox.innerHTML = listData;
}