I'm teaching myself JavaScript, and I thought it would be fun to make a DnD character generator for my friends and I to use. I want to use this DnD api (http://www.dnd5eapi.co/docs/#overview) to fetch classes, races, alignments, etc, but the reading I've done on apis has been kind of confusing, and I don't really know how to apply it.
I want to build a series of dropdown menus where we can select class, race, and alignment, and also have a checkbox next to each one with the option to randomize it instead. I know I have to write fetch function for it, but this is where I'm lost. How do I actually write the fetch function that will populate those dropdown menus from the api?
Whilst you can do this with vanilla JavaScript, it's much easier with JQuery. You can populate the dropdowns by making some GET requests to the API to get the data, then creating an <option> for each item in the results.
$(document).ready(function() {
// The things we want to get
const fetchItems = [{
"endpoint": "/classes",
"id": "#class"
},
{
"endpoint": "/races",
"id": "#race"
},
{
"endpoint": "/alignments",
"id": "#alignment"
}
];
// For each category to fetch
$.each(fetchItems, function(i, item) {
// Get the data
$.get("https://www.dnd5eapi.co/api" + item.endpoint, function(data) {
// For each row in the data
$.each(data.results, function(j, row) {
// Create a new option in the corresponding <select>
$(item.id).append($("<option>", {
value: row.index,
text: row.name
}));
});
});
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form>
<label for="class">Class:</label>
<select name="class" id="class"></select>
<label for="race">Race:</label>
<select name="race" id="race"></select>
<label for="alignment">Alignment:</label>
<select name="alignment" id="alignment"></select>
</form>
</body>
</html>