teamallnighter
teamallnighter

Reputation: 77

using select to set a filter on api data

scratching my head on this one. I'd like to be able to apply a filter based on a tag. I am using the poke api and have the data displaying and have it sorted by ID. What i'd like to do is have the user select the "type" if pokemon from the tag and have the page filter based on that (keeping the sort). If the user dosnt select anything it would just show all 150.

I apologize in an advance for being a total noob!

<!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>Quick's Pokedex</title>
        <link rel="stylesheet" href="style.css" />
        <link rel="stylesheet" href="/css/animate.css" />
        <link href="https://fonts.googleapis.com/css?family=Rubik&display=swap" rel="stylesheet"/>
        <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.12.1/css/all.css" integrity="sha384-TxKWSXbsweFt0o2WqfkfJRRNVaPdzXJ/YLqgStggBVRREXkwU7OKz+xXtqOU4u8+" crossorigin="anonymous">
    </head>
    <body>
        <div class="header">
            <img src="/assets/img/two.png" alt="Pokemon Logo" height="500" class="animated fadeInLeftBig logo" id="logo">
        </div>
        <div class="container">
            <h3 class="full-experience">Get the full experience!    <i class="fas fa-level-down-alt"></i></h3>
            <audio class="audio-player" loop src="/assets/audio/pokemon.mp3" controls> Error: your web browser does not support this audio player. </audio>
            <h1 class="quicks-h1">Quick's Pokedex</h1>
            <div class="sorting">
                <h2>Sorting</h2>
                <p>Select at least one type</p>
                <div class="custom-select" style="width:200px;">
                    <select>
                    <option value="0">Select Type:</option>
                    <option value="1">Bug</option>
                    <option value="2">Dragon</option>
                    <option value="3">Electric</option>
                    <option value="4">Fairy</option>
                    <option value="5">Normal</option>
                    <option value="6">Psychic</option>
                    <option value="7">Fighting</option>
                    <option value="8">Water</option>
                    <option value="9">Fire</option>
                    <option value="10">Flying</option>
                    <option value="11">Ice</option>
                    <option value="12">Poison</option>
                    <option value="13">Rock</option>
                    <option value="14">Grass</option>
                    <option value="15">Ground</option>
                    </select>
                </div>
                <br>
                <div class="custom-select" style="width:200px;">
                    <select><option value="16">Sort By:</option>
                        <option value="17">Name</option>
                        <option value="18">ID</option>
                        </select>
              </div>
              <br>
              <button class="sort-btn">GO!</button>
            </div>
        <div class="pokedex-div">
            <ul class="pokedex" id="pokedex"></ul>
        </div>
    </div>
<script src="app.js"></script>
<script src="dropdown.js"></script>
    </body>
</html>

Here is the app.js I did make an attempt at the bottom to set up filtering but cant seem to figure it out.

// //Main API Call//

const pokedex = document.getElementById('pokedex');
const fetchPokemon = () => {
    const promises = [];
    for (let i = 1; i <= 150; i++) {
        const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        promises.push(fetch(url).then((res) => res.json()));
    }
    Promise.all(promises).then((results) => {
        const pokemon = results.map((result) => ({
            name: result.name,
            image: result.sprites['front_default'],
            type: result.types.map((type) => type.type.name).join(', '),
            id: result.id
        })).sort((a, b) => a.id > b.id ? 1 : -1);
        displayPokemon(pokemon);
    });
};
const displayPokemon = (pokemon) => {
    const pokemonHTMLString = pokemon
        .map(
            (pokeman) => `
    <li class="card">
        <img class="card-image" src="${pokeman.image}"/>
        <h2 class="card-title">${pokeman.id}. ${pokeman.name}</h2>
        <p class="card-subtitle">Type: ${pokeman.type}</p>
    </li>
`
        )
        .join('');
    pokedex.innerHTML = pokemonHTMLString;
};
fetchPokemon();

const filterPokemon = pokemon.filter() => {
    const myDropDown = document.querySelector('#myDropDown')
}

I also have a dropdown.js... I doubt anyone needs it but it is here:

var x, i, j, selElmnt, a, b, c;
/* Look for any elements with the class "custom-select": */
x = document.getElementsByClassName("custom-select");
for (i = 0; i < x.length; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  /* For each element, create a new DIV that will act as the selected item: */
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected");
  a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /* For each element, create a new DIV that will contain the option list: */
  b = document.createElement("DIV");
  b.setAttribute("class", "select-items select-hide");
  for (j = 1; j < selElmnt.length; j++) {
    /* For each option in the original select element,
    create a new DIV that will act as an option item: */
    c = document.createElement("DIV");
    c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {
        /* When an item is clicked, update the original select box,
        and the selected item: */
        var y, i, k, s, h;
        s = this.parentNode.parentNode.getElementsByTagName("select")[0];
        h = this.parentNode.previousSibling;
        for (i = 0; i < s.length; i++) {
          if (s.options[i].innerHTML == this.innerHTML) {
            s.selectedIndex = i;
            h.innerHTML = this.innerHTML;
            y = this.parentNode.getElementsByClassName("same-as-selected");
            for (k = 0; k < y.length; k++) {
              y[k].removeAttribute("class");
            }
            this.setAttribute("class", "same-as-selected");
            break;
          }
        }
        h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
    /* When the select box is clicked, close any other select boxes,
    and open/close the current select box: */
    e.stopPropagation();
    closeAllSelect(this);
    this.nextSibling.classList.toggle("select-hide");
    this.classList.toggle("select-arrow-active");
  });
}

function closeAllSelect(elmnt) {
  /* A function that will close all select boxes in the document,
  except the current select box: */
  var x, y, i, arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");
  for (i = 0; i < y.length; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i)
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < x.length; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}

/* If the user clicks anywhere outside the select box,
then close all select boxes: */
document.addEventListener("click", closeAllSelect);\

Upvotes: 1

Views: 1921

Answers (1)

EugenSunic
EugenSunic

Reputation: 13693

Filtered by electric type for example:

const pokedex = document.getElementById('pokedex');
const fetchPokemon = () => {
  const promises = [];
  for (let i = 1; i <= 150; i++) {
    const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
    promises.push(fetch(url).then((res) => res.json()));
  }
  Promise.all(promises).then((results) => {
    const pokemon = results.map((result) => ({
      name: result.name,
      image: result.sprites['front_default'],
      type: result.types.map((type) => type.type.name).join(', '),
      id: result.id
    })).sort((a, b) => a.id > b.id ? 1 : -1);
    console.log('sadfa',pokemon)
    const filteredPokemonsByType= pokemon.filter(x=>x.type==='electric');
    console.log('Filtered by eletric', filteredPokemonsByType);

  });
};

fetchPokemon()

Here is your full example with the dropdown: https://jsfiddle.net/fkq43gbu/

Upvotes: 1

Related Questions