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
JavaScript
x
15
15
1
<form id= 'selectionForm' action="#">
2
<p>
3
<label>
4
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
5
<span>Netflix</span>
6
</label>
7
</p>
8
<p>
9
<label>
10
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
11
<span>Amazon Prime Video</span>
12
</label>
13
</p>
14
</form>
15
Advertisement
Answer
Edit : this snippet fetch every checked element and send a request for each one.
JavaScript
1
18
18
1
<script lang="js" >
2
3
document.getElementById('fetch').addEventListener('click', function (e) {
4
e.preventDefault();
5
let checkedElements = document.querySelectorAll('.filled-in:checked');
6
7
let outputContainer = document.getElementById('output');
8
9
for (let e of checkedElements) {
10
fetch('https://api.publicapis.org/entries').then((r) => r.json()).then( (d) => {
11
let outputContent = document.createTextNode('The checked element is : '+e.id+'<br>'+d.entries[0].Description)
12
outputContainer.appendChild(outputContent)
13
})
14
}
15
16
17
})
18
</script>
JavaScript
1
17
17
1
<form id= 'selectionForm' action="#">
2
<p>
3
<label>
4
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
5
<span>Netflix</span>
6
</label>
7
</p>
8
<p>
9
<label>
10
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
11
<span>Amazon Prime Video</span>
12
</label>
13
</p>
14
<input type="button" value="Fetch" id="fetch">
15
<div id="output"></div>
16
17
</form>
This is what you are looking for ? This example get Data from an API and display a field bellow the first checkbox :
JavaScript
1
15
15
1
<script lang="js" >
2
3
document.getElementById('Netflix').addEventListener('click', function (e) {
4
e.preventDefault();
5
let outputText = '';
6
let outputContainer = document.getElementById('output');
7
8
fetch('https://api.publicapis.org/entries').then((r) => r.json()).then( (d) => {
9
let outputContent = document.createTextNode(d.entries[0].Description)
10
outputContainer.appendChild(outputContent)
11
12
})
13
14
})
15
</script>
JavaScript
1
15
15
1
<form id= 'selectionForm' action="#">
2
<p>
3
<label>
4
<input type="checkbox" class="filled-in" name="Nexflix" id="Netflix" />
5
<span>Netflix</span>
6
</label>
7
<div id="output"></div>
8
</p>
9
<p>
10
<label>
11
<input type="checkbox" class="filled-in" name="Prime" id="Prime"/>
12
<span>Amazon Prime Video</span>
13
</label>
14
</p>
15
</form>