I have a JSON file
names.json
["Ant Man", "Aquaman", "Iron Man", "John Wick", "Superman"]
Now this file is a few MiB large which has a hundred thousand names. This file is exported as JSON serialized format from a database which has a history of names typed into the input box.
Here is a simple HTML page to replicate an input
index.html
<!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<div>
Enter Name:
</div>
<div>
<input type="text" />
</div>
</body>
</HTML>
This page is new, it does not have any history of the input tags nor will it submit any form to create new history, I only want to load the data I provide it.
How would I go about loading the autocomplete suggestions? Can someone please suggest?
Something that works which looks like –
Desired output
globalThis.namelist = JSON.parse("names.json");
console.log(globalThis.namelist.length);
<input type="text" list="globalThis.namelist" />
And does not take too many lines of code to solve a missing attribute for datalist tag support for JS lists. Hard Coding the options without reading the JSON is not allowed or I would have done it. Thank you.
- Load the JSON file with a script tag to deserialize(a step in unmarshalling) the data.
<script src="names.json"></script>
- Then populate a datalist tag with option tags using vanilla JS.
<datalist id="name-suggest"></datalist>
Should work with a few MiB of data to autocomplete in real time.
Here are the updated files
names.json
globalThis.namelist = ["Ant Man", "Aquaman", "Iron Man", "John Wick", "Superman"]
Update the names.json file to store it’s value in browser variable namelist.
HTML file now has datalist tag to be populated.
It should also load the names.json
as script and save it in globalThis.namelist
.
window.onload = function() {
globalThis.myenv = {};
globalThis.namelist = ["Ant Man", "Aquaman", "Iron Man", "John Wick", "Superman"]
// above line is substitute for script tags.
globalThis.myenv.addToDatalist = function(datalistID, datalist) {
let suggest = "";
for (name of datalist) {
suggest = suggest + "<option value ="" + name + ""></option>";
}
document.getElementById(datalistID).innerHTML = suggest;
};
globalThis.myenv.postload = function() {
console.log(globalThis.namelist.length);
globalThis.myenv.addToDatalist("name-suggest", globalThis.namelist);
console.log("ready!");
};
globalThis.myenv.postload();
}
<!DOCTYPE HTML>
<HTML>
<head>
</head>
<body>
<div>
Enter Name:
</div>
<div>
<input type="text" list="name-suggest"/>
</div>
<datalist id="name-suggest">
</datalist>
<!--
<script src="names.json"></script>
<script src="index.js"></script>
I am commenting this line because code snippet will not run it.
Replace the line in js with script tag commented here.
-->
</body>
</HTML>
Now you can type in the text box and the names should be suggested in real time.