Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Actively update DOM on keyup in an input, check to see if the input value is included as a value within properties of an array of objects

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}`)
    });

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading