Below is the code I have written to create an InputFilter.
MyFilter = function(args) {
var dataUrl = args.url;
var divID = args.divID;
var div = document.getElementById(divID);
var myTable = '<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">' +
'<ul id="myUL">' + '<li>' + '<a href="#"></a>' + '</li>' + '</ul>';
div.innerHTML = myTable;
function foo(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "data.json", true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
callback(httpRequest.responseText);
}
};
httpRequest.send();
}
foo(function(data) {
debugger;
var jsonc = JSON.parse(data);
var new_opt = "";
for (i = 0; i < jsonc.length; i++) {
new_opt += '<li><a href="#">' + jsonc[i]['VALUE'] + '</a></li>';
}
document.getElementById('myUL').innerHTML = new_opt;
});
myFunction = function() {
debugger;
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
}
I need help to modify the code so that when a list item is clicked, it gets selected and displayed in the input field like a combo box.
You can find the fiddle version of my code here.
Note : Currently, the code allows searching. I want to implement selection and display functionality as well.
In another project, similar behavior is implemented using a table. The code snippet for that is:
document.querySelectorAll('#myTable tr:not(.header)').forEach(function(_tr) {
_tr.addEventListener('click', function() {
document.getElementById('myInput').value += " ; " + this.getElementsByTagName('td')[0].textContent;
});
});
The goal is to click on items of the a
tag and have the selected items displayed in the input tag with ;
separation.