Inject the JavaScript template into an HTML page within a <div> element

Looking for a solution to format JSON API data listing books with title, author, and other properties into HTML? Utilizing ES6 backticks and JavaScript templating, the challenge arises when needing to display two cards per row on the HTML page. The issue lies in ensuring that each card iteration is placed within an opening and closing row div every two iterations. While attempting different methods such as using variables and functions with return statements, a simpler approach is sought. Any suggestions for a more efficient way to achieve this task would be greatly appreciated! Thank you.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8>
    <title>Book Finder</title>
      <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <div id="title" class="center">
        <h1 class="text-center mt-5">Book Finder</h1>
        <div class="row">
          <div id="input" class="input-group mx-auto col-lg-6 col-md-8 col-sm-12">
            <input id="search-box" type="text" class="form-control" placeholder="Search Books!...">
            <button id="search" class="btn btn-primary" onclick="">Search</button>
          </div>
        </div>
      </div>
     <div class="book-list">
       <h2 class="text-center">Search Result</h2>
         <div id="list-output" class="">
           <div class="row">
             <div class="col-lg-6">
               <div class="card" style="">
                 <div class="row no-gutters">
                   <div class="col-md-4">
                     <img src="" class="card-img" alt="...">
                   </div>
                   <div class="col-md-8">
                      <div class="card-body">
                        <h5 class="card-title">Book Title</h5>
                        <p class="card-text">Author</p>
                        <p class="card-text"><small class="text-muted">Publisher: </small></p> 
                        <a href="${bookLink}" class="btn btn-secondary">More Info</a>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

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

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script src="js/index.js"></script>
  </body>
</html>

$(document).ready(function() {
      // ... JavaScript code omitted for brevity 
    });
    
    function formatOutput(title, author, publisher, bookLink, bookImg) {
      var htmlCard1 = `<div class="col-lg-6">
      // ... Remaining JavaScript code snipped for clarity  
      return htmlCard1;
    }

Answer №1

I made some revisions by removing unnecessary lines, but feel free to add them back if needed. The code below should now function as expected.

       $(document).ready(function () {
            var item, tile, author, publisher, bookLink, bookImg;
            var outputList = $("#list-output");

            //listener for search button
            $("#search").click(function () {
                var searchData = $("#search-box").val();
                if (searchData === "") {
                    // displayErr();
                } else {
                    console.log(searchData);
                    $.get("https://www.googleapis.com/books/v1/volumes?q=" + searchData, function (response) {
                        for (var i = 0; i < response.items.length; i++) {
                            item = response.items[i];
                            title = item.volumeInfo.title;
                            author = item.volumeInfo.authors;
                            publisher = item.volumeInfo.publisher;
                            bookLink = item.selfLink;
                            bookImg = item.volumeInfo.imageLinks.thumbnail;
                            // in production code, item.text should have the HTML entities escaped.
                            var html;
                            if ((response.items.length % 2 != 0) && (i == response.items.length - 1)) {
                                html = "";
                                html += "<div class='row'>";
                                html += formatOutput(title, author, publisher, bookLink, bookImg);
                                html += "</div>";
                                outputList.append(html);
                            }
                            else {
                                if (i % 2 == 0) {
                                    html = "";
                                    html += "<div class='row'>";
                                }

                                html += formatOutput(title, author, publisher, bookLink, bookImg);

                                if (i % 2 != 0) {
                                    html += "</div>";
                                    outputList.append(html);
                                }
                            }
                        }
                    });
                }
            });

        });



        function formatOutput(title, author, publisher, bookLink, bookImg) {
            // console.log(title + ""+ author +" "+ publisher +" "+ bookLink+" "+ bookImg)
                var htmlCard1 = `<div class="col-lg-6">
                <div class="card" style="">
                  <div class="row no-gutters">
                    <div class="col-md-4">
                      <img src="${bookImg}" class="card-img" alt="...">
                    </div>
                    <div class="col-md-8">
                      <div class="card-body">
                        <h5 class="card-title">${title}</h5>
                        <p class="card-text">Author: ${author}</p>
                        <p class="card-text"><small class="text-muted">Publisher: ${publisher}</small></p>
                        <a href="${bookLink}" class="btn btn-secondary">More Info</a>
                      </div>
                    </div>
                  </div>
                </div>
              </div>`
            return htmlCard1;
        }

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

Exploring CryptoJS in a Vue.js project

https://github.com/brix/crypto-js I successfully installed CryptoJS using npm i crypto-js. However, I am facing difficulty in integrating it into my project. When I attempt to use the following code: // Decrypt var bytes = CryptoJS.AES.decrypt(cipher ...

Interact with embedded elements in JavaScript by using the onClick event

Here is a JavaScript code snippet I've been working on: <div> <tr onClick="click1()"> <td> click 1 </td> <td onClick="click2()"> click 2 < ...

Click the "Login" button using Jquery to gain access

Whenever I hit the Login button, a 500 Internal server error pops up in the console. Can someone guide me on the correct way to perform a POST request using jQuery? I would really appreciate any help. <button class="login100-form-btn" type=& ...

How can I modify the mesh structure in Three.js?

Having two meshes, mesh1 and mesh2, each with the same number of vertices and extrusion. mesh1 = 5000 vertices. mesh2 = 5000 vertices. I transfer the vertices from mesh2 to mesh1. Then I execute: mesh2.geometry.verticesNeedUpdate = true; mesh2.geometry. ...

Expanding the content within the modal body in Twitter-Bootstraps does not increase its size

Here's the code snippet that I'm working with: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-conte ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

Innovative form creation using Vue.js

My interactive form allows users to input an item, quantity, and cost per item like this: <form @submit.prevent="submit"> <div class="form-group" v-for="(input,k) in inputs" :key="k"> <input ty ...

Obtaining HTML data with ajax within a WordPress post

Greetings! I've been putting together a website and I'm eager to include a unique timeline in each of my posts. I'm utilizing WordPress for this project. However, since the timeline I want to insert will vary from post to post, I am unable t ...

Keeping calculated values in the React state can cause issues

In an attempt to develop a component resembling a transferlist, I have simplified the process substantially for this particular issue. Consider the following example: the react-admin component receives two inputs - a subset of selected items record[source ...

Ways to stop a ng-click event on a child div controller from activating an ng-click in the parent controller?

http://plnkr.co/edit/gB7MtVOOHH0FBJYa6P8t?p=preview The example above demonstrates a parent-child controller setup. In the child controller, when a button is clicked, it displays the div showPop and emits an event to the $rootScope. Upon receiving this e ...

Sending data from form inputs to an array using the GET method

I'm trying to pass an array from form inputs (checkboxes) using the get method. In my AJAX call, I have the following code: var subcat_checked = new Array(); $.each($("input[name='subcategories']:checked"), function() { subcat_checked.p ...

Accessing data from an ever-changing table

I am currently working with a dynamically created table using Datatables. foreach ($results as $value) { echo ' <tr> <td>'.$value->object_name.'</td> ...

Creating a tree structure from an array in JavaScript, including the parent id enclosed in brackets

Before dismissing this question as a duplicate, please listen to me. I am working with a json response in reactjs that looks like the following organisationUnits: [ { name: "0.Mzondo", id: "nW4j6JDVFGn", parent: { ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

Preserving classes in JQuery after making AJAX requests

Before we proceed, it's important to note that I am unable to modify any of the existing calls, code, or functions. This means I must come up with a workaround solution. So, here's the situation: I have a form containing various fields and a dro ...

true not redirecting to 404 page when axios request fails

I have implemented Axios to access a basic API. My goal is to direct the user to the default Next.js 404 page in case of a failed request with a 404 error code. I have set the notFound boolean to true if the request status is 404. There are a total of 10 u ...

Dynamic rule addition with JQuery Validation

I am searching for a method to dynamically incorporate the jQuery validation rules, as they are needed in various locations. For instance, a user can edit news in two different ways. The first method involves using a standard form with jQuery validation, ...

What methods and technologies are accessible for executing JavaScript through PHP?

Are there any frameworks or tools available to execute JavaScript from PHP? Is there a similar project like the Harmony project for PHP? I am interested in running JS unit tests (or even BDD) directly from PHP, as demonstrated in this post (for Ruby). Am ...

Using jQuery to fetch LDAP data and return it in JSON format

I am encountering an issue with a returned JSON value. When the LDAP result is valid, the JSON return is also OK but when the result is invalid, the JSON becomes invalid as well. I am using UWamp and I am new to this. Thank you all. PHP code : <?php ...

Positioning the subheading "perfectly beneath the main heading" for a clean and professional look

I'm feeling a bit lost when it comes to tasks like this. While I can easily design an entire website using html and css, I start to question my approach when faced with challenges like these. Could someone offer some guidance? My goal is to have a H1 ...