Home > OS >  How to target selected radio buttons?
How to target selected radio buttons?

Time:08-20

Below is my code and I am getting movies data from an API and I am creating different elements using Javascript create Element like title, rating and favorite radio button for selecting favorite movies now I wonder how to target all the selected radio buttons because I have generated radio buttons dynamically and its getting very hard to target those radio buttons:

const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?&api_key=04c35731a5ee918f014970082a0088b1&query=";
const apiUrl = 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1';
const IMGPATH = "https://image.tmdb.org/t/p/w1280";

const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");

showMovies(apiUrl);

function showMovies(url) {
  fetch(url)
    .then((res) => res.json())
    .then(function(data) {
      console.log(data.results);
      data.results.forEach((element) => {
        let movYear = new Date(element.release_date);

        const el = document.createElement("div");
        const image = document.createElement("img");
        const title = document.createElement("h2");
        const year = document.createElement("h2");
        const rank = document.createElement("h2");
        const node = document.createTextNode("Favrouite: ")

        const wrapper = document.createElement("h2");
        const fav = document.createElement("INPUT");

        fav.setAttribute("type", "radio");
        fav.setAttribute("id", element.id);

        wrapper.insertBefore(node, wrapper.children[0]);
        wrapper.appendChild(fav);
        title.innerHTML = `Title:  ${element.title}`;
        year.innerHTML = `Release:  ${movYear.getFullYear()}`;
        rank.innerHTML = `Rating:  ${element.popularity}`;
        image.src = IMGPATH   element.poster_path;

        el.appendChild(image);
        el.appendChild(title);
        el.appendChild(year);
        el.appendChild(rank);

        el.appendChild(wrapper);
        main.appendChild(el);
      });
    });
}

form.addEventListener("submit", (e) => {
  e.preventDefault();
  main.innerHTML = "";

  let searchTerm = search.value;


  if (searchTerm) {
    showMovies(SEARCHAPI   searchTerm)
    search.value = "";
  } else if (!searchTerm) {
    showMovies(apiUrl)
  } else {
    main.innerHTML = "<h1>No result Found!</h1>";
  }

});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Moive</title>
  <link rel="stylesheet" href="style.css" />
  <script type="module" src="JS/script.js"></script>
</head>

<body>
  <header>
    <a href="index.html">
      <h1>Movies</h1>
    </a>

    <form id="form" name="form" autocomplete="off">
      <input type="text" id="search" placeholder="Search"  autofocus />
      <button type="submit">Submit</button>
    </form>

  </header>
  <main id="main"></main>
</body>

</html>

CodePudding user response:

You can delegate

const title = document.createElement("h2");
title.classList.add("title");
fav.setAttribute("type", "radio");
fav.setAttribute("id", element.id);
fav.classList.add("fav")

main.addEventListener("click",function(e) {
  const tgt = e.target;
  if (tgt.matches(".fav")) {
    console.log(tgt.closest("div").querySelector("h2.title").textContent);
  }
})

To get all the favourites, you can use a map:

const allFavs = [...main.querySelectorAll(".fav:checked")].map(rad => rad.closest("div").querySelector("h2.title").textContent);

const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?&api_key=04c35731a5ee918f014970082a0088b1&query=";
const apiUrl = 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1';
const IMGPATH = "https://image.tmdb.org/t/p/w1280";

const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");

main.addEventListener("click",function(e) {
  const tgt = e.target;
  if (tgt.matches(".fav")) {
    console.log("clicked",tgt.closest("div").querySelector("h2.title").textContent);
        const allFavs = [...main.querySelectorAll(".fav:checked")].map(rad => rad.closest("div").querySelector("h2.title").textContent);
    console.log("current favs",allFavs)
  }
})

showMovies(apiUrl);

function showMovies(url) {
  fetch(url)
    .then((res) => res.json())
    .then(function(data) {
      // console.log(data.results);
      data.results.forEach((element) => {
        let movYear = new Date(element.release_date);

        const el = document.createElement("div");
        const image = document.createElement("img");
        const title = document.createElement("h2");
        title.classList.add("title");
        const year = document.createElement("h2");
        const rank = document.createElement("h2");
        const node = document.createTextNode("Favourite: ")

        const wrapper = document.createElement("h2");
        const fav = document.createElement("INPUT");

        fav.setAttribute("type", "radio");
        fav.setAttribute("id", element.id);
        fav.classList.add("fav")

        wrapper.insertBefore(node, wrapper.children[0]);
        wrapper.appendChild(fav);
        title.innerHTML = `Title:  ${element.title}`;
        year.innerHTML = `Release:  ${movYear.getFullYear()}`;
        rank.innerHTML = `Rating:  ${element.popularity}`;
        image.src = IMGPATH   element.poster_path;

        el.appendChild(image);
        el.appendChild(title);
        el.appendChild(year);
        el.appendChild(rank);

        el.appendChild(wrapper);
        main.appendChild(el);
      });
    });
}

form.addEventListener("submit", (e) => {
  e.preventDefault();
  main.innerHTML = "";

  let searchTerm = search.value;


  if (searchTerm) {
    showMovies(SEARCHAPI   searchTerm)
    search.value = "";
  } else if (!searchTerm) {
    showMovies(apiUrl)
  } else {
    main.innerHTML = "<h1>No result Found!</h1>";
  }

});
img { height: 150px }
<header>
    <a href="index.html">
      <h1>Movies</h1>
    </a>

    <form id="form" name="form" autocomplete="off">
      <input type="text" id="search" placeholder="Search"  autofocus />
      <button type="submit">Submit</button>
    </form>

  </header>
  <main id="main"></main>

  • Related