I'm working with this API: http://hp-api.herokuapp.com/api/characters, which returns an array of objects. I have an input in my HTML that has an "keyup" event listener.
document.getElementById('search').addEventListener('keyup', filterWizards)
Goal: I want to actively search through the array of objects returned from the API to see if the name or house properties value includes the text from the input element. Then I will filter out the DOM to include information based on what is typed
Example: If a user started typing Harry Potter; "Har..." my program will start searching through each object from the array of objects to see whether the object includes "Har" as part of the text from the name or house property. Or maybe they had the intention of searching a house like Gryffindor, as they started typing Gryffindor I could filter through the array of objects and choose to do things like display the characters on my DOM that meet the criterion
Data Returned From API:
let characters = 'http://hp-api.herokuapp.com/api/characters';
fetch(characters)
.then(res => res.json()) // parse response as JSON
.then(data => {
console.log(data);
})
.catch(err => {
console.error(`error ${err}`)
});
CodePudding user response:
Assuming an input field with an id of "input", you can filter the results to match the value of the input field:
<input id="input">
<script>
fetch(characters)
.then(res => res.json()) // parse response as JSON
.then(data => {
console.log(data);
let re = new RegExp(document.getElementById('input').value);
let matches = data.filter(function(elmt){
return elmt.name.match(re);
});
console.log(matches);
})
.catch(err => {
console.error(`error ${err}`)
});
</script>
CodePudding user response:
Here's what I would do:
- Disable the search field until data is available.
- Populate a
datalist
with the search matches which you find usingfilter
and atoLowerCase()
comparison (sohar
findsHarry Potter
).
const search = document.getElementById('search'), characters = document.getElementById('characters');
let searchList;
fetch('http://hp-api.herokuapp.com/api/characters')
.then(res => res.json()) // parse response as JSON
.then(data => {
searchList = data;
enableSeach(data);
updateDatalist('');
})
.catch(err => {
console.error(`error ${err}`)
});
function enableSeach(data) {
search.disabled = false;
search.placeholder = 'Type to search';
search.addEventListener('input', () => {
updateDatalist(search.value);
});
}
function updateDatalist(searchTerm) {
characters.innerHTML = '';
searchList.filter(char => char.name.toLowerCase().includes(searchTerm.toLowerCase())).forEach(({name}) => {
let option = document.createElement('option');
option.value = name;
characters.append(option);
})
}
<input id="search" type="search" placeholder="Fetching data..." disabled list="characters" autocomplete="false">
<datalist id="characters"></datalist>