There seems to be an issue with the proper loading of jQuery and JS functions onto

I'm trying to update my webpage dynamically using jQuery and JavaScript, but I am facing problems with loading the content. I have created 4 distinct objects and I want to display each object's content on the page by calling a function with specific arguments (book1, book2, album1, album2). My goal is to have the page load the objects and their respective content in this order: book1, book2, album1, album2.

Currently, when I load the page, I see the "name", "category", and "price" values from book2 (Life of Pi), along with the "selling_points" values from book1 repeated on all four divs instead.

*Whenever I check the console, I encounter an "Uncaught TypeError: Cannot read property 'forEach' of undefined" error for the "product.selling_points.forEach(function(point)" segment of my code.

Furthermore, I am unsure about how to include each object's respective picture_url; currently, I am directly adding the image URL I wish to use for book1 to every div.

body {
  background-color: green;
}
#header {
  background-color: red;
  font-size:300%;
  text-align: center;
  color: purple;
  font-weight: bold;
}
#navbar {
  background-color:blue;
  text-align: center;
}
#content {
  background-color: red;
  text-align: center;
  font-size:150%;
  font-style: oblique;
  color:darkblue;
}
#book1 {
  background-color: red;
  font: black;
}
#book2 {
  background-color: red;
  font: black;
}
#album1 {
  background-color: red;
  font: black;
}
#album2 {
  background-color: red;
  font: black;
}
.image {
  height:600px;
  width:420px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
p {
  font-size:120%;
  text-align: center;
}
.name {
  font-size: 150%;
}
  background-color: red;
  font: black;
}
#album1 {
  background-color: red;
  font: black;
}
#album2 {
  background-color: red;
  font: black;
}
.image {
  height:600px;
  width:420px;

}
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styles.css">
  <title>Blamazon</title>
</head>
<body>
<div id="header">BLAMAZON</div><br>
<div id="content">Products</div><br>
  <div id="book1">
    <p class="name"></p>
    <p class="category"></p>
    <p class="price"></p>
    <img class="image">
    <p class="description"></p>
  </div>
  <div id="book2">
    <p class="name"></p>
    <p class="category"></p>
    <p class="price"></p>
    <img class="image">
    <p class="description"></p>
  </div>
  <div id="album1">
    <p class="name"></p>
    <p class="category"></p>
    <p class="price"></p>
    <img class="image">
    <p class="description"></p>
  </div>
  <div id="album2">
    <p class="name"></p>
    <p class="category"></p>
    <p class="price"></p>
    <img class="image">
    <p class="description"></p>
  </div>

<div id="footer"></div>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<script>
var book1, book2, album1, album2

book1 = {
    product_id: 'book1',
    "name": "Thinking Fast and Slow",
    "category": "Non-Fiction",
    "picture_url": "http://ecx.images-amazon.com/images/I/51oXKWrcYYL.jpg",
    "price": "$7.07",
    "selling_points": ["This will help you make better decisions!", "Understand how humans make the wrong decisions so often"]
}

book2 = {
    product_id: 'book2',
    "name": "The Life of Pi",
    "category": "Fiction",
    "picture-url": "http://bestfreebooks.org/wp-content/uploads/2015/07/Life-of-Pi-Yann-Martel.jpg",
    "price": "$9.07",
    "selling_points": ["This will make you never want to get on a boat with a tiger...", "And understand the meaning of life!"]
}

album1 = {
    product_id: 'album1',
    "name": "Back in Black, AC DC",
    "category": "Hard Rock",
    "picture_url": "https://upload.wikimedia.org/wikipedia/commons/b/be/Acdc_backinblack_cover.jpg",
    "price": "$12.07",
    "selling_points": ["Oldie but a goodie", "Will help you rock out"]
}

album2 = {
    product_id: 'album2',
    "name": "Good kid maad city",
    "category": "Hip-Hop",
    "picture_url": "http://ecx.images-amazon.com/images/I/51Zzc7PUDML._SY300_.jpg",
    "price": "$12.07",
    "selling_points": ["A sprawling masterpiece of technical rapping and structured storytelling", "Defies and expands the conventions of the genre"]
}

var add_product = function(product) {
    var $prod = $('#' + product.product_id)
    $prod.find('.name').text(product.name)
    $prod.find('.category').text(product.category)
    $prod.find('.image').attr('src','http://ecx.images-amazon.com/images/I/51oXKWrcYYL.jpg')
    $prod.find('.price').text(product.price)
    product.selling_points.forEach(function(point) {
        $prod.find('.description').append("<div><br>" + point + "</div><br>")
    })
}

add_product(book1)
add_product(book2)
add_product(album1)
add_product(album2)

/*
  var add_product = function(product) {
    $('.name').text(product.name)
    $('.category').text(product.category)
    $('.image').attr('src','http://ecx.images-amazon.com/images/I/51oXKWrcYYL.jpg')
    $('.price').text(product.price)
    product.selling_points.forEach(function(point) {
      $('.description').append("<div><br>" + point + "</div><br>")
    })
  }

  add_product(book1)
  add_product(book2)
  add_product(album1)
  add_product(album2)
*/
</script>
</body>
</html>

Answer №1

It appears that there is a simple typo in your code related to the album1 variable – it seems you have used selling-points instead of selling_points. The script loading seems to be functioning correctly. The reason why the description, etc., are showing up in incorrect places is because $(.classname) targets all elements on the page with that particular class name. To resolve this issue, consider adding a qualifier such as a product_id and then finding the class name relative to that qualifier. This can be done like so:

var book1, book2, album1, album2

book1 = {
    product_id: 'book1',
    "name": "Thinking Fast and Slow",
    "category": "Non-Fiction",
    "picture_url": "http://ecx.images-amazon.com/images/I/51oXKWrcYYL.jpg",
    "price": 7.07,
    "selling_points": ["This will help you make better decisions!", "Understand how humans make the wrong decisions so often"]
}

book2 = {
    product_id: 'book2',
    "name": "The Life of Pi",
    "category": "Fiction",
    "picture-url": "http://bestfreebooks.org/wp-content/uploads/2015/07/Life-of-Pi-Yann-Martel.jpg",
    "price": 9.07,
    "selling_points": ["This will make you never want to get on a boat with a tiger...", "And understand the meaning of life!"]
}

album1 = {
    product_id: 'album1',
    "name": "Back in Black, AC DC",
    "category": "Hard Rock",
    "picture_url": "https://upload.wikimedia.org/wikipedia/commons/b/be/Acdc_backinblack_cover.jpg",
    "price": 12.07,
    "selling_points": ["Oldie but a goodie", "Will help you rock out"]
}

album2 = {
    product_id: 'album2',
    "name": "Good kid maad city",
    "category": "Hip-Hop",
    "picture_url": "http://ecx.images-amazon.com/images/I/51Zzc7PUDML._SY300_.jpg",
    "price": 12.07,
    "selling_points": ["A sprawling masterpiece of technical rapping and structured storytelling", "Defies and expands the conventions of the genre"]
}

var add_product = function(product) {
    var $prod = $('#' + product.product_id)
    $prod.find('.name').text(product.name)
    $prod.find('.category').text(product.category)
    $prod.find('.image').attr('src','http://ecx.images-amazon.com/images/I/51oXKWrcYYL.jpg')
    $prod.find('.price').text(product.price)
    product.selling_points.forEach(function(point) {
        $prod.find('.description').append("<div><br>" + point + "</div><br>")
    })
}

add_product(book1)
add_product(book2)
add_product(album1)
add_product(album2)

Answer №2

Do not load the jQuery file within a .js file and do not include <script></script> tags in your file as they are not necessary and might cause issues with the file being read.

Instead, load the JS code directly within your HTML.

If you must load jQuery into the JS file, consider using the following code:

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-2.1.1.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

Keep in mind that this just adds the code to your HTML anyway.

// JavaScript code snippet
      var book1, book2, album1, album2

      // Objects for books and albums
      book1 = {
        "name": "Thinking Fast and Slow",
        "category": "Non-Fiction",
        "picture_url": "http://ecx.images-amazon.com/images/I/51oXKWrcYYL.jpg",
        "price": 7.07,
        "selling_points": ["This will help you make better decisions!", "Understand how humans make the wrong decisions so often"]
      }

      // More object declarations...

      // Function to add product information
      var add_product = function(product) {
        $('.name').text(product.name)
        $('.category').text(product.category)
        $('.image').attr('src','http://ecx.images-amazon.com/images/I/51oXKWrcYYL.jpg')
        $('.price').text(product.price)
        product.selling_points.forEach(function(point) {
          $('.description').append("<div><br>" + point + "</div><br>")
        })
      }

      // Adding product details to HTML
      add_product(book1)
      add_product(book2)
      add_product(album1)
      add_product(album2)
// CSS styling rules
      body {
        background-color: green;
      }
      // More styling rules...
      .image {
        height:600px;
        width:420px;
      }
<html>
      <head>
        <link rel="stylesheet" type="text/css" href="styles.css">
        <title>Blamazon</title>
        <script src="https://code.jquery.com/jquery-2.1.1.js"></script>
      </head>
      <body>
        <div id="header">BLAMAZON</div><br>
        <div id="content">Products</div><br>

        // Product containers in HTML
        <div id="book1">
          <p class=name></p>
          <p class=category></p>
          <p class=price></p>
          <img class="image"></p>
          <p class="description"></p>
        </div>
        // More product containers...

        <div id="footer"><div>
    

Remember to check your browser's console log for any JavaScript errors in the future.

Answer №3

var novel1, novel2, music1, music2;

novel1 = {
    "name": "The Alchemist",
        "genre": "Fiction",
        "picture_url": "http://ecx.images-amazon.com/images/I/51oXKWrcYYL.jpg",
        "price": 10.99,
        "selling_points": ["A magical tale of self-discovery and destiny", "Will inspire you to follow your dreams"],
    add: function () {
        $('#novel1 .name').text(this.name);
        $('#novel1 .genre').text(this.genre);
        $('#novel1 .price').text(this.price);
        $('#novel1 .image').attr('src', this.picture_url);
        $('#novel1 .name').text(this.name);
        this.selling_points.forEach(function (point) {
            $('#novel1 .description').append("<div><br>" + point + "</div><br>");
        });
    }
}

novel2 = {
    "name": "1984",
        "genre": "Dystopian Fiction",
        "picture_url": "http://bestfreebooks.org/wp-content/uploads/2015/07/Life-of-Pi-Yann-Martel.jpg",
        "price": 8.99,
        "selling_points": ["A chilling portrayal of a totalitarian regime", "Raises questions about surveillance and government control"],
    add: function () {
        $('#novel2 .name').text(this.name);
        $('#novel2 .genre').text(this.genre);
        $('#novel2 .price').text(this.price);
        $('#novel2 .image').attr('src', this.picture_url);
        $('#novel2 .name').text(this.name);
        this.selling_points.forEach(function (point) {
            $('#novel2 .description').append("<div><br>" + point + "</div><br>");
        });
    }
}

music1 = {
    "name": "Thriller, Michael Jackson",
        "genre": "Pop",
        "picture_url": "https://upload.wikimedia.org/wikipedia/commons/b/be/Acdc_backinblack_cover.jpg",
        "price": 14.50,
        "selling_points": ["One of the best-selling albums of all time", "Iconic songs that defined an era"],
    add: function () {
        $('#music1 .name').text(this.name);
        $('#music1 .genre').text(this.genre);
        $('#music1 .price').text(this.price);
        $('#music1 .image').attr('src', this.picture_url);
        $('#music1 .name').text(this.name);
        this.selling_points.forEach(function (point) {
            $('#music1 .description').append("<div><br>" + point + "</div><br>");
        });
    }
}

music2 = {
    "name": "My Beautiful Dark Twisted Fantasy",
        "genre": "Rap",
        "picture_url": "http://ecx.images-amazon.com/images/I/51Zzc7PUDML._SY300_.jpg",
        "price": 11.99,
        "selling_points": ["Innovative production and introspective lyrics", "Pushes boundaries in hip-hop"],
    add: function () {
        $('#music2 .name').text(this.name);
        $('#music2 .genre').text(this.genre);
        $('#music2 .price').text(this.price);
        $('#music2 .image').attr('src', this.picture_url);
        $('#music2 .name').text(this.name);
        this.selling_points.forEach(function (point) {
            $('#music2 .description').append("<div><br>" + point + "</div><br>");
        });
    }
}

novel1.add();
novel2.add();
music1.add();
music2.add();

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

Securing form submissions in Express JS: Best practices for protecting your data

In order to enhance security, the loginform.html located in the public folder sends the username and password input by the user to a server route '/login' for authentication. Server-Side Code: var express = require('express'); var app ...

What is the method for activating a song by clicking a button?

Is it possible to create a button that matches the theme of my website for controlling the song being played with the audio controls? Here is the current code I am using: <audio controls autoplay loop> <source src="Main Theme.mp3" ...

Activate expansive pop-up windows with primeng's dynamic dialog feature

In my Angular web application, I am using the PrimeNg modal extension to display modal popups. I have successfully passed a component to the modal service with the following code: const ref = this.dialogService.open(LogsComponent, { data: { ...

Exploring the capabilities of React testing-library for interacting with the DOM within a React application

I've been working on developing custom developer tools after finding inspiration from Kent C Dodds' insightful article here. One of the challenges I encountered was automatically populating values in a form that I created. My approach involved u ...

Error Encountered: Angular JS Throwing Unhandled Injection Error

I am having trouble validating the fields in my index.html and js files. I keep seeing errors, even after trying different versions of angular-route.min.js and angular.js. AngularJs | Basic Login Form <body ng-app="myApp"> ...

Executing a closure within a promise's callback

Currently, I am working on implementing a queue system for a web application in order to locally store failed HTTP requests for later re-execution. After reading Mozilla's documentation on closures in loops, I decided to create inner closures. When ...

What is the best way to condense text within a header and still maintain right-aligned buttons?

I'm having trouble using css to position some buttons on the right side of my header, while also ensuring that the text collapses if it becomes as wide as the buttons. I want to maintain justification and show ellipsis for the main text of the breadcr ...

Tips for enclosing the "body" element using a background image

Hey there! I'm a newbie web developer with a casual approach to coding. I'm trying to jazz up my menu by adding a background image, but no matter what I do, it keeps showing the default white background. Can anyone lend me a hand? If you're ...

Is the jqm flipswitch with the label on the left and the switch on the right?

My goal is to display multiple flipswitches on a mobile app page. This is the code I am using: <div class="ui-content"> <form> <fieldset> <div data-role="fieldcontain"> <label for="checkbox-based-flipswitch" ...

Adjusting the OrbitControl target in a React environment

I attempted to create a model using react-three-fiber and react-drei, but the OrbitControl target setting is causing it to appear too high. import React, { useRef, useState, Suspense, useEffect } from 'react' import { Canvas, useFrame, useLoader, ...

Verify that the JSON data contains the desired data type before adding it to jQuery

I'm working with JSON data extracted from an Excel file. I need to match the First Name in the JSON data with the 'First Name' field and append those elements to a specific div. Additionally, if the JSON data includes a 'status', I ...

What is the method for eliminating <ol> elements that have a particular number of <

As a beginner in the world of html and css, I am reaching out for some assistance. My question is regarding how to remove the ol tags that contain 3 li elements without any class or id. Here is an example: <div class="text"> <ol> ...

What is the preferred convention for defining AngularJS directives as "attributes" versus "elements"?

When creating Angular directives, I've noticed that some directives could also be defined as either an HTML element or an attribute. I'm curious to know what the community convention is for choosing between the two, and the reasons behind it. Fo ...

Unable to send an HTTP request using intent

I'm currently facing an issue where an intent triggers an HTTP request, but I keep encountering errors. Whenever the intent is triggered, the following code is executed: const https = require('https'); https.get('*************' ...

Utilizing AngularJS: Dynamically employ custom directives for enhanced reusability

I am currently developing my debut single page Angular.js application and finding myself in a bit of a rut when it comes to programmatically compiling/evaluating a custom directive to insert it into the DOM from within a controller. The custom directive I ...

Preventing users from selecting past dates in HTML input date field

I need help with disabling past dates in an HTML date input field. Even though I am able to restrict selecting past dates on the date picker, I can still save data if I manually type in a previous date (e.g., 12/08/2020). $(document).ready(function() { ...

Implement automatic calculation by utilizing ajax to fetch values from the database whenever there is a change

I am completely lost on how to effectively make use of this. My initial thought is to implement JavaScript arrays. So, I have a select option available with values fetched from the database, and the select options are dynamic. By clicking on the "add row" ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

Utilizing callback functions with JSONP in jQuery

Utilizing jQuery scripts to fetch a JSON feed from Flickr and YouTube in order to dynamically generate HTML on my WordPress website is the current approach I am taking. To pull data from Flickr, I am using: <!-- Script for retrieving photos from Flickr ...

Creating a cutting-edge single page web application with the MERN stack: A comprehensive guide

After researching various articles on building dynamic apps with Express.js using technologies like EJS and Handlebars, I have decided that I want my web app to be dynamic and single page by utilizing React instead. My goal is to render templates and inse ...