As a user when I submit this form I want a fetch call for each checkbox that is checked So that I can load information from the API depending on what the selections are.
Using Materialize framework and jquery or plain javascript is fine. Hard question to explain but on form submit I want to bring up information depending on checkbox ticked. Each checkbox should trigger a fetch call to the specific API which will then append data to the new page such as movies availbe on nexflix or amazon prime
<form id= 'selectionForm' action="#">
<p>
<label>
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
<span>Netflix</span>
</label>
</p>
<p>
<label>
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
<span>Amazon Prime Video</span>
</label>
</p>
</form>
Advertisement
Answer
Edit : this snippet fetch every checked element and send a request for each one.
<script lang="js" >
document.getElementById('fetch').addEventListener('click', function (e) {
e.preventDefault();
let checkedElements = document.querySelectorAll('.filled-in:checked');
let outputContainer = document.getElementById('output');
for (let e of checkedElements) {
fetch('https://api.publicapis.org/entries').then((r) => r.json()).then( (d) => {
let outputContent = document.createTextNode('The checked element is : '+e.id+'<br>'+d.entries[0].Description)
outputContainer.appendChild(outputContent)
})
}
})
</script><form id= 'selectionForm' action="#">
<p>
<label>
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
<span>Netflix</span>
</label>
</p>
<p>
<label>
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
<span>Amazon Prime Video</span>
</label>
</p>
<input type="button" value="Fetch" id="fetch">
<div id="output"></div>
</form>This is what you are looking for ? This example get Data from an API and display a field bellow the first checkbox :
<script lang="js" >
document.getElementById('Netflix').addEventListener('click', function (e) {
e.preventDefault();
let outputText = '';
let outputContainer = document.getElementById('output');
fetch('https://api.publicapis.org/entries').then((r) => r.json()).then( (d) => {
let outputContent = document.createTextNode(d.entries[0].Description)
outputContainer.appendChild(outputContent)
})
})
</script><form id= 'selectionForm' action="#">
<p>
<label>
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
<span>Netflix</span>
</label>
<div id="output"></div>
</p>
<p>
<label>
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
<span>Amazon Prime Video</span>
</label>
</p>
</form>