Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
Javascript Search Bar with Star Wars API

I am new and would need help to get on with my code. I want to be able to write a movie title from the API and then filter it, and only show the related results after input some text. Can someone help me? This is my code.

const films = document.getElementById('films');
const searchBar = document.getElementById('searchBar');
let StarwarsFilms = [];

searchBar.addEventListener('keyup', (e) => {
    const searchString = e.target.value.toLowerCase();

    const filteredTitel = StarwarsFilms.filter((title) => {
        return (
          title.toLowerCase().includes(searchString)
        );
    });
    displaytitle(filteredTitel);
});

const loadTitle = async () => {
    try {
        const res = await fetch('https://swapi.dev/api/films/');
        StarwarsFilms = await res.json();
        displaytitle(StarwarsFilms);
    } catch (err) {
        console.error(err);
    }
};

const displaytitle = (title) => {
    const htmlString = title
        .map((results) => {
            return `
            <li class="title">
                <h2>${results.title}</h2>
            </li>
        `;
        })
        .join('');
        films.innerHTML = htmlString;
};

loadTitle();
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Star Wars</title>
    </head>
    <body>
        <div class="container">
            <h1>Search</h1>
            <div id="searchWrapper">
                <input
                    type="text"
                    name="searchBar"
                    id="searchBar"
                    placeholder="search for a character"
                />
            </div>
            <ul id="films"></ul>
            <ul id="starwarstitle"></ul>
        </div>
        <script src="starwars.js"></script>
    </body>
</html>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In loadTitle:

StarwarsFilms = await res.json();

returns an object that looks like

{count: 6, next: null, previous: null, results: [/*details omitted*/]}

I presume you wanted to find the results of the search, so it should be:

StarwarsFilms = (await res.json()).results;

Next, in the keyup listener for searchBar:

title.toLowerCase().includes(searchString)

Here, title is actually a "film" object (that includes many keys), not the title string itself, so you want:

title.title.toLowerCase().includes(searchString)

Final code (with some variable renaming for clarity):

const films = document.getElementById('films');
const searchBar = document.getElementById('searchBar');
let starWarsFilms = [];

searchBar.addEventListener('keyup', (e) => {
    const searchString = e.target.value.toLowerCase();

    const filteredFilms = starWarsFilms.filter((film) => {
        return (
          film.title.toLowerCase().includes(searchString)
        );
    });
    displayTitles(filteredFilms);
});

const loadTitle = async () => {
    try {
        const res = await fetch('https://swapi.dev/api/films/');
        starWarsFilms = (await res.json()).results;
        displayTitles(starWarsFilms);
    } catch (err) {
        console.error(err);
    }
};

const displayTitles = (results) => {
    const htmlString = results
        .map((film) => {
            return `
            <li class="title">
                <h2>${film.title}</h2>
            </li>
        `;
        })
        .join('');
        films.innerHTML = htmlString;
};

loadTitle();
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Star Wars</title>
    </head>
    <body>
        <div class="container">
            <h1>Search</h1>
            <div id="searchWrapper">
                <input
                    type="text"
                    name="searchBar"
                    id="searchBar"
                    placeholder="search for a character"
                />
            </div>
            <ul id="films"></ul>
            <ul id="starwarstitle"></ul>
        </div>
        <script src="starwars.js"></script>
    </body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda