What I want to do I'm building a simple UI where you can search dynamically in an array with plain Javascript. The results list are links to fetch data from a Django backend with AJAX and show the details in a modal.
What I get The results list from the search works fine. But if I click on the links, the AJAX function isn't triggered.
If I try the same link directly in the HTML (not generated by Javascript) it works fine and the function is called.
Note Don't pay attention to the Django part of the thing. I just want to know why the AJAX function is not called when I generate the link in the Javascript list.
Any clues welcome. Thanks in advance!
let arr = ["anagrams-of-string-(with-duplicates)", "array-concatenation", "array-difference", "array-includes",]
function updateResult(query) {
let resultList = document.querySelector(".result");
resultList.innerHTML = "";
arr.map(function(algo){
query.split(" ").map(function (word){
if(algo.toLowerCase().indexOf(word.toLowerCase()) != -1){
resultList.innerHTML += `<li class="list-group-item">
<a href="" id="${algo}" data-id="${algo}" class="artist-title show_product" style="color: black; padding-left: 0;" data-toggle="modal">${algo}test</a>
</li>`;
console.log("This works fine");
}
})
})
}
$(function(){
$('.show_product').on('click', function (e) {
e.preventDefault();
let product_id = $(this).attr('id');
console.log("This function is called");
$.ajax({
url:'/backend/form-fill/',
type:'POST',
data: $('#form_have_product_'+product_id).serialize(),
success:function(response){
console.log(response);
$('.show_product').trigger("reset");
openModal(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function getFormData(content_data){
$('#categoria_producto').text(content_data.field1);
$('#estatus_contenido').text(content_data.field2);
$('#descripcion_brief').text(content_data.field3);
$('#descripcion_long').text(content_data.field4);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group" style="position: fixed; top: 0; z-index: 10;">
<input oninput="updateResult(this.value)" style="font-size: 3rem; height: 15vh;" type="search" class="form-control" placeholder="Search..." />
</div>
<div>
<ul class="list-group result" style="margin-top: 15vh;"></ul>
</div>
</div>