Refresh list whenever a key is pressed

Having trouble updating the list after fetching API data.

The list should only display results that start with the typed letter.

Any assistance would be greatly appreciated :)

Below is my JavaScript 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 the 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>

Answer №1

Give this a shot. Here's the HTML code:

<!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 here is the associated JavaScript code:

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

Alternatively, if you prefer keyup events for specific 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);
        });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the Ajax response value consistently 1?

I am facing an issue where a JavaScript in an HTML page is sending two variables to a PHP script, which then echoes one of the variables at the end. However, the response value always remains 1. Despite trying methods like alerting, console.log, and puttin ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

JavaScript code for sorting a table based on a time interval

There is an index file with a flight schedule table. The table allows sorting by airline and departure time, as well as filtering by airline name. I'm trying to figure out how to add filtering by time range, specifically departing flights between 8 AM ...

How can I combine these scripts that are not working simultaneously?

I have two scripts on my site that are based on the meta title, and I'm trying to make them work together. I thought changing the function names would be enough, but when I use both scripts, one doesn't work. Why is this happening? Also, should I ...

At what specific times is it most appropriate to use parentheses when dealing with functions?

Check out my code snippet below: const cleanRoom = function() { return new Promise(function(resolve, reject) { resolve('Cleaned The Room'); }); }; const removeGarbage = function(message) { return new Promise(function(resolve, reject) ...

Executing statements within a loop sequentially in jQuery: Best practices

I'm working on developing a program that will display different images in a loop when clicked. To achieve this functionality, I implemented jQuery to trigger a function upon clicking an image, which then cycles through all the images by updating the " ...

Instructions for rearranging the configuration of a 2D array?

A 2-dimensional array is created from a string called matrix: 131 673 234 103 018 201 096 342 965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 037 331 After parsing, it becomes an array of arrays like this: [ [131, 673, 234, 103, 018], [2 ...

Generating dynamic anchor tags in Vue.JS

I have a JavaScript object that I want to convert into HTML elements and display it in Vue.js. So far, my approach has been to convert the object into strings representing HTML elements and then add them to the template. However, even though this method di ...

Guide on organizing an array of objects by the sub-part of their property values

Is there a way to order the elements in the given array based on a custom criteria related to the last 3 letters of 'prop2' in descending order? The specific order should be 'ABR', 'FDE', 'ZFR'. Another array needs t ...

Navigate to a list item once Angular has finished rendering the element

I need to make sure the chat box automatically scrolls to the last message displayed. Here is how I am currently attempting this: akiRepair.controller("chatCtrl", ['$scope', function($scope){ ... var size = $scope.messages.length; var t ...

Stacked divs experiencing layout issues in Firefox browser

An innovative book animation has been crafted, showcasing flipping pages with a clever use of z-index to stack the pages. While everything displays correctly in the browser UI, an interesting situation arises when inspecting elements. In Firefox, selectin ...

Mastering the art of MUI V4: Implementing conditional row coloring

I've encountered an issue with my basic Material UI v4 datagrid. I'm attempting to change the color of any row that has an age of 16 to grey using color: 'grey'. However, I'm finding it challenging to implement this. The documentat ...

Display Vue component using a string input

Is there a solution to make this non-functioning example work, or is its usage illegal? Vue.component('hello', { template: '<span>Hello world!</span>' }) Vue.component('foo', { data(){ return { ...

How can I navigate through all the divs by setting an interval slider with a random starting point?

I have a Jsonp request that returns a block of HTML with the following structure: <div id="slider_wrapper" style=""> <div style="xxx" ><section style="xx">xx</section></div> <div style="xxx" ><section style=" ...

Traversing JSON Data using Vanilla JavaScript to dynamically fill a specified amount of articles in an HTML page

Here is the code along with my explanation and questions: I'm utilizing myjson.com to create 12 'results'. These results represent 12 clients, each with different sets of data. For instance, Client 1: First Name - James, Address - 1234 Ma ...

What is the mechanism behind the functionality of promise chains?

I stumbled upon this code on SO and decided to debug it in order to enhance my understanding of the promise concept. However, I am facing an issue with the code below where the last 'then' function is only fetching the tweet with id=4 instead of ...

Transferring information between an ASP web form page and an Angular2 application

Currently, I am working on a project that involves dealing with a legacy WebForms system. The system is gradually being updated to Angular 2, but the transition is happening incrementally. In order to effectively integrate information from the legacy sect ...

What sets apart utilizing a constructor versus state = {} for defining state in a react component?

There are two ways to declare state in a class component as shown below: class App extends Component { constructor(props) { super(props); this.state = { name: 'John' } } render() { return ...

Using THREE.js to incorporate a stroke above extruded text

Looking to enhance text with a horizontal line above it: var geo = new THREE.TextGeometry("x", geometry_options); var mat = new THREE.MeshBasicMaterial({color: 0, side:THREE.DoubleSide}); geo.computeBoundingBox (); var vec = new THREE.Shape(); vec.moveTo( ...

Utilizing ReadableStream as a body for mocking the HTTP backend in unit testing for Angular 2

Looking to simulate the http backend following this helpful guide. This is my progress so far: Test scenario below describe('DataService', () => { beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ ...