I'm trying to create a search box that will essentially autocomplete based on user input from a key-value pair in a json file. It looked like using datalist might be the best option for this, but when I execute the code below, no option tags appear in the html.
I am still pretty new to jquery and json, so I'm WAY open to suggestions.
Here's the json. The list contains 1450 items if that's relevant:
{ "osCars": [
{ "id": 1,
"name": "Cadillac",
"type": "Sedan",
"desc": "A fine American automobile"
},
{ "id": 2,
"name": "BWM",
"type": "Sedan",
"desc": "A fine German automobile"
},
{ "id": 3,
"name": "Lexus",
"type": "Sedan",
"desc": "A fine Japanese automobile"
}
]}
Here's the html:
<input type="text" maxlength="30" list="carList" id="carSearchBox" name="carSearchBox" pattern="[A-Za-z '-]*$" placeholder="search cars" autofocus autocomplete="on">
<datalist id="carList"></datalist>
<script src="js/main.js"></script>
<script>window.onload=getCars;</script>
And here's the javascript/jquery:
function getCars() {
var url, carOption;
url = 'js/cars.json';
$.getJSON(url, function(data) {
//populate the cars datalist
$(data.osCars).each(function() {
carsOption = "<option value=\"" + this.id + "\">" + this.name + "</option>";
$('#carList').append(carsOption);
});
});
}