I'm having some problems with list update after fetching API.
After each new letter the list should update and show only results that begin with typed letter.
Please help :)
Here is my JS code:
var input = document.getElementById('input');
input.addEventListener('keyup', getJson);
function getJson() {
fetch('https://itunes.apple.com/search?term=indie&entity=song')
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
let result = '';
data.results.forEach(function (song) {
result += `<li>${song.artistName} - ${song.trackName}</li>`;
});
document.getElementById('result').innerHTML = result;
})
.catch(function (empty) {
console.log(empty);
});
}
Here is HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search songs</title>
</head>
<body>
<div id="app">
<h1>Enter artist name or song:</h1>
<input type="text" id="input">
<div class="loader"></div>
<br><br>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Just try this. this is your html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search songs</title>
</head>
<body>
<div id="app">
<h1>Enter artist name or song:</h1>
<input type="text" id="term" placeholder="term">
<input type="text" id="entity" placeholder="entity">
<div class="loader"></div>
<br><br>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
and javascript:
var term = document.getElementById('term');
var entity = document.getElementById('entity');
document.addEventListener('keyup', getJson);
function getJson() {
fetch('https://itunes.apple.com/search?term='+term.value+'&entity='+entity.value)
.then(function (response) {
return response.json();
})
.then(function (data) {
let result = '';
try{
data.results.forEach(function (song) {
console.log(song);
result += `<li>${song.artistName} - ${song.trackName}</li>`;
});
}
catch{}
document.getElementById('result').innerHTML = result;
})
.catch(function (empty) {
console.log(empty);
});
}
or if you want keyup event for certain elements:
var term = document.getElementById('term');
var entity = document.getElementById('entity');
let termAndEntity = [term, entity];
termAndEntity.forEach(function(element){
element.addEventListener('keyup', getJson);
});
function getJson() {
fetch('https://itunes.apple.com/search?term='+term.value.toLowerCase()+'&entity='+entity.value.toLowerCase())
.then(function (response) {
return response.json();
})
.then(function (data) {
let result = '';
try{
data.results.forEach(function (song) {
console.log(song);
result += `<li>${song.artistName} - ${song.trackName}</li>`;
});
}
catch{}
document.getElementById('result').innerHTML = result;
})
.catch(function (empty) {
console.log(empty);
});
}