I am currently working on populating a dropdown menu with the values of the 'styleName' field from a JSON data file.
Here is an example of my JSON data:
{"name":{"styleName":"name","fillType":"none","fillTrans":"0","outlineType":"solid","outlineWidth":"1","outlineColor":"#ff0000"}}
{"sarah":{"styleName":"sarah","fillTrans":"none","fillTrans":"0","outlineType":"solid","outlineWidth":"1","outlineColor":"#ff0000"}}
//....
Below you can see the JavaScript code I have written for this purpose.
let dropdown = document.getElementById('tem');
dropdown.length = 0;
let defaultOption = document.createElement('option');
defaultOption.text = 'Choose Template';
dropdown.add(defaultOption);
dropdown.selectedIndex = 0;
const url = '../../templates.json';
fetch(url)
.then(
function(response) {
if (response.status !== 200) {
console.warn('There seems to be a problem. Status Code: ' +
response.status);
return;
}
response.json().then(function(data) {
let option;
console.log(data);
for (let i = 0; i < data.length; i++) {
option = document.createElement('option');
option.text = data[i].styleName;
dropdown.add(option);
}
});
}
)
.catch(function(err) {
console.error('Fetch Error -', err);
});
Despite receiving a 200
response, I keep encountering the following error and the dropdown menu remains empty:
Error:
Uncaught (in promise) SyntaxError: Unexpected token { in JSON at position xxx
Promise.then (async)
(anonymous) @ VM8493:22
Promise.then (async)
(anonymous) @ VM8493:13
The select element for the dropdown looks like this:
<select id="tem" class='w150'>
</select>