3

I am calling data from API and listing the data by name. I want to search and add object by name from the list (using Add Fav Movie button) and store the entire data of that object in an array using native javascript.

I can do this in Angularjs , but less idea using native javascript.

function addListItem(title, listId) {
  var ul = document.getElementById(listId);
  var li = document.createElement("li");
  li.className = 'list-group-item';
  li.appendChild(document.createTextNode(title));
  ul.appendChild(li);
}

function afterLoad() {
    var data = JSON.parse(this.responseText);
    var name = document.createElement('img');
    
    const results = data.results;
     
    // loop through items
    results.forEach(item => {
      addListItem(item.title, "items");
    });
    
    name.src = data.title;
    document.body.appendChild(name);
    }

function afterClick() {
    // changed target to focus search
    var terms = document.getElementById("search").value.split(' ').join('+');
    var request = new XMLHttpRequest();
    request.addEventListener('load', afterLoad);
    request.open('GET', 'https://api.themoviedb.org/3/search/movie?api_key=8318c431b4fc8a2c4762bf2a52c351ee&query='+terms);
    request.send();

    }

button.addEventListener("click", afterClick);
<!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">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"/>
  <title>Get Movies</title>
</head>
<body>
  <header id="main-header" class="bg-success text-white p-4 mb-3">
    <div class="container">
      <h1 id="header-title">Get Movies<span style="display:none">123</span></h1>
		<input style="align:right" type="text" class="form-control mr-2" id="search">
		<input type="submit" class="btn btn-dark" value="Search" id="button">
    </div>
  </header>
  <div class="container">
   <div id="main" class="card card-body">
    <h2 class="title">Add Fav Movies</h2>
    <form class="form-inline mb-3">
      <input type="text" class="form-control mr-2">
      <input type="submit" class="btn btn-dark" value="Submit">
    </form>
    <h2 class="title">Lists</h2>
    <ul id="items" class="list-group">
      
    </ul>
   </div>
  </div>
  </body>
</html>

On response JSON I want to select object of movie (which I click on list ) under array key result. And append that particular movie object on another array. How can I do this ?

6
  • What problem are you facing with the current code? Commented Apr 24, 2019 at 6:00
  • @randomSoul not facing problem , I am not getting how to search and pass the object in an array. Commented Apr 24, 2019 at 6:03
  • I'am not really clear about what are you trying to achieve. You mean, you want to find the details of movie object entered by the user in search (movie name). Commented Apr 24, 2019 at 6:07
  • @randomSoul No, I can search the movie and get lists of movies in <li> as you can see. Now I want to type the particular movie name from that list on Add Fav movies input and when I click add , the object related to that particular movie name must get stored in an array. Commented Apr 24, 2019 at 6:11
  • Okay. But your Lists is empty. check your above code. Commented Apr 24, 2019 at 6:15

4 Answers 4

1

When you type movie name in input (Favourite movies) and hit the submit, check if the input has any value. If it has, then make the array of textContent of your favourite movie list and then apply the filter to get movie objects whose name match the user entered value

function addListItem(title, listId) {
  var ul = document.getElementById(listId);
  var li = document.createElement("li");
  li.className = 'list-group-item';
  li.appendChild(document.createTextNode(title));
  ul.appendChild(li);
}

let results;

function afterLoad() {
    var data = JSON.parse(this.responseText);
    var name = document.createElement('img');
    
    results = data.results;
     
    // loop through items
    results.forEach(item => {
      addListItem(item.title, "items");
    });
    
    name.src = data.title;
    document.body.appendChild(name);
}

function afterClick() {
    // changed target to focus search
    var terms = document.getElementById("search").value.split(' ').join('+');
    var request = new XMLHttpRequest();
    request.addEventListener('load', afterLoad);
    request.open('GET', 'https://api.themoviedb.org/3/search/movie?api_key=8318c431b4fc8a2c4762bf2a52c351ee&query='+terms);
    request.send();
}

button.addEventListener("click", afterClick);

const submitBtn = document.querySelector('input[value="Submit"]');
const favMovie = document.querySelector('form > input');

submitBtn.addEventListener('click', function(e) {
    e.preventDefault();
    const favMovieName = favMovie.value;
    if(favMovieName.length > 0) {
        const filteredFavMovies = results.filter(({title}) => title.toLowerCase().includes(favMovieName.toLowerCase()));
        console.log(filteredFavMovies);
    }
});
<header id="main-header" class="bg-success text-white p-4 mb-3">
    <div class="container">
        <h1 id="header-title">Get Movies<span style="display:none">123</span></h1>
        <input style="align:right" type="text" class="form-control mr-2" id="search">
        <input type="submit" class="btn btn-dark" value="Search" id="button">
    </div>
</header>
<div class="container">
    <div id="main" class="card card-body">
        <h2 class="title">Add Fav Movies</h2>
        <form class="form-inline mb-3">
            <input type="text" class="form-control mr-2">
            <input type="submit" class="btn btn-dark" value="Submit">
        </form>
        <h2 class="title">Lists</h2>
        <ul id="items" class="list-group">

        </ul>
    </div>
</div>

Sign up to request clarification or add additional context in comments.

6 Comments

Exactly , but I want to pass entire object of of that particular movie not only name. Check what you get in API result array in console.
@NoobCoder - Apply filter directly to the results array, because your favorite list have only movie title. See edit.
Why it is creating multiple array for each entry.
@NoobCoder - Because, it is not necessary that the user type exactly movie name, might be he can type few initials or other from movie name. I have used includes, so it will check whether user inputted movie name is present in the the title property. If you want exact match, then you can remove includes and match using === operator, but in this case if the user type partial movie name, then no results would be retrieved.
If the answer solves your problem, mark it as accepted so as to indicate that problem has been resolved.
|
1

You can use Array.filter to create a new array with only selected items.

var filteredItems = allItems.filter(item => {

   if (itesm.year > 1980)
     return true
   else
     return false;

})

OR

you can use the Array.forEach method to traverse through the original array and do whatever you want with the items:

allItems.forEach(item => {
   if (item.year > 1980)
      addListItem(item.title, "items");

})

Comments

0

As I understood you correct, you want the movies object from themoviedb and append all results to the list items?

First you need to replace:

    request.addEventListener('load', afterLoad);

with:

    request.onload = afterLoad;

and then need to really define the button.. here is a working example:

function addListItem(title, listId) {
  var ul = document.getElementById(listId);
  var li = document.createElement("li");
  li.className = 'list-group-item';
  li.appendChild(document.createTextNode(title));
  ul.appendChild(li);
}

function afterLoad() {
  var data = JSON.parse(this.responseText);
  var name = document.createElement('img');

  const results = data.results;

  // loop through items
  results.forEach(item => {
    addListItem(item.title, "items");
  });

  name.src = data.title;
  document.body.appendChild(name);
}

function searchMovie() {
  var terms = document.getElementById("search").value.split(' ').join('+');
  var request = new XMLHttpRequest();
  request.onload = afterLoad;
  request.open('GET', 'https://api.themoviedb.org/3/search/movie?api_key=8318c431b4fc8a2c4762bf2a52c351ee&query=' + terms);
  request.send();
}

var button = document.getElementById('button');
button.addEventListener("click", searchMovie);
<header id="main-header" class="bg-success text-white p-4 mb-3">
  <div class="container">
    <h1 id="header-title">Get Movies<span style="display:none">123</span></h1>
    <input style="align:right" value="Avengers" type="text" class="form-control mr-2" id="search">
    <input type="submit" class="btn btn-dark" value="Search" id="button">
  </div>
</header>
<div class="container">
  <div id="main" class="card card-body">
    <h2 class="title">Add Fav Movies</h2>
    <form class="form-inline mb-3" action="/" method="POST">
      <input type="text" class="form-control mr-2">
      <input id="submit" type="submit" class="btn btn-dark" value="Submit">
    </form>
    <h2 class="title">Lists</h2>
    <ul id="items" class="list-group">

    </ul>
  </div>
</div>

1 Comment

No , I can list from the moviedb based on search but now I want to select a particular movie and add the object data related to selected movie on another array and so on.. it keeps on adding while selecting , just like adding favourites from the list.
0

You can also check by jsfiddle https://jsfiddle.net/somnath640/emov3yxs/1/

I have removed 2nd form and added ID for both 2nd bottom and input fields. and added another function call against the 2nd button hit.

function addListItem(title, listId) {
  var ul = document.getElementById(listId);
  var li = document.createElement("li");
  li.className = 'list-group-item';
  li.appendChild(document.createTextNode(title));
  ul.appendChild(li);
}

function afterLoad() {
    var data = JSON.parse(this.responseText);
    var name = document.createElement('img');
    
    const results = data.results;
     
    // loop through items
    results.forEach(item => {
      addListItem(item.title, "items");
    });
    
    name.src = data.title;
    document.body.appendChild(name);
    }

function afterClick() {
    // changed target to focus search
    var terms = document.getElementById("search").value.split(' ').join('+');
    console.log(terms);
    var request = new XMLHttpRequest();
    request.addEventListener('load', afterLoad);
    request.open('GET', 'https://api.themoviedb.org/3/search/movie?api_key=8318c431b4fc8a2c4762bf2a52c351ee&query='+terms);
    request.send();

    }
    
    
function addToList(){
	var favMovieName = document.getElementById("fabinput").value;
  addListItem(favMovieName, "items");
  console.log(favMovieName);
}

button.addEventListener("click", afterClick);

addfav.addEventListener("click", addToList);
<!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">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"/>
  <title>Get Movies</title>
</head>
<body>
  <header id="main-header" class="bg-success text-white p-4 mb-3">
    <div class="container">
      <h1 id="header-title">Get Movies<span style="display:none">123</span></h1>
		<input style="align:right" type="text" class="form-control mr-2" id="search">
		<input type="submit" class="btn btn-dark" value="Search" id="button">
    </div>
  </header>
  <div class="container">
   <div id="main" class="card card-body">
    <h2 class="title">Add Fav Movies</h2>
    
      <input type="text" class="form-control mr-2" id="fabinput">
      <input type="submit" class="btn btn-dark" id="addfav" value="Add">

    <h2 class="title">Lists</h2>
    <ul id="items" class="list-group">
      
    </ul>
   </div>
  </div>
  </body>
</html>

1 Comment

Your search button is itself adding the first name from the list. The addFav button must add. Also I want the entire object of that particular movie in a separate array. Not on the list example :- [ {object of movie avatar}, {object of movie rambo first blood}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.