I'm doing an autocomplete functionality which fills a datalist with options comprised of an endpoint query, which is working properly. But I have a problem in the end of my ajax call where my function is affecting only the last element of an array, as opposed to the correct one that is being clicked. I'm trying to make sure that when the user clicks their selection in the list, it sends certain values of the object into form input fields to save.
Right now, when i click an option it does put the correct object values into the form, HOWEVER, they are the values that correspond to the final element in the array and not the clicked one.
I've commented where my issue starts, but this is the whole script for reference. Again, the list fills correctly (though a little slow) and the click does fill out the form inputs, but the values are not corresponding to the clicked option, just the last in the array.
What am I doing wrong here?
<script type="text/javascript">
//If user types, send their input in ajax POST on each keystroke
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
//their input is searchResult
const searchResult = $(this).val();
$.ajax({ //url
data: {
search_result:searchResult
},
type: "POST",
success: function(response){
//empty out old responses
$('#returnedProducts').empty();
//this starts my index
let searchResult = response.hits.hits;
for(let i = 0; i < searchResult.length; i++) {
//this puts matches into the datalist option, which works
$("#returnedProducts").append("<option value=" + searchResult[i]._source.category + ">" + searchResult[i]._source.category + "</option>");
/*This block is my issue*/
$("#productInput").on('input', function(){
var val = this.val = this.value;
if($('#returnedProducts option').filter(function(){
return this.value === val;
}).length){
//These elements do fill, but the values correspond to only the last array item, not the clicked one
document.getElementById("grpName").value = searchResult[i]._source.frm.grp.grp_name;
document.getElementById("grpNum").value = searchResult[i]._source.frm.grp.grp_code;
}
})
/*end of problem block*/
}
}
});
}
});
</script>
document.getElementById, for readability and such. And maybe avoid using potentially ambiguous statements such asvar val = this.val = this.value;And you might end up solving the problem as well.