I use JSON data to create the <options>
of a <select>
:
jsonOptions.forEach(function(item) {
var option = document.createElement('option');
option.text = item.description;
option.value = item.product;
dataList.appendChild(option);
});
But I find it very ugly to have this inside the code, I mounted this one first to see if it worked, even because this JSON will have almost 2000 items.
So I saved my JSON to a separate file and tried to include an external file as follows:
[
{"description": "Carro 1"},
{"description": "Carro 2", "product": "4"},
{"description": "Carro 3", "product": "4"},
{"description": "Carro 4", "product": "4"},
{"description": "Carro 5", "product": "4"},
{"description": "Carro 6", "product": "4"}
]
$.getJSON("js/carros.json", function(item) {
var option = document.createElement('option');
option.text = item.description;
option.value = item.product;
dataList.appendChild(option);
});
In addition to the correct way to save the file and call it, another question I have is with the jQuery library call.
Do I need to call it inside the JavaScript that I am running the code or the fact that it is present there in the HTML means that it has already been loaded?
Continuing the answers given, some questions have arisen regarding the algorithm.
$.getJSON('js/carros.json', function(err, data) {
if (err !== null) {
console.log('Ocorreu um erro' + err);
} else {
alert("chegou aqui!")
console.log(data);
}
});
I am using this code, and it is displaying the error in the Console:
jquery-2.1.0.js:8556 Failed to load file:///C:/Users/Alexandre/Desktop/Projeto%20Colet%C3%A2nea/New/js/carros.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Checking the path where the JSON file is, is correct.
Another question that came up, where do I fit the forEach
?