Adding Elements to an Array with JavaScript

I am currently working on simulating a mailbox using Materialize for the design. In my collection view, I want to add cells dynamically, but I need help with appending HTML using JavaScript.

  <div class="row" id="mailBox">
          <div class="container col s7">
            <div class="collection-header center">
              <h4>Email Box</h4>
            </div>
            <ul class="collection with-header" id="mailCollection">
              <!-- Start: Dynamically Adding Cells To this View -->
              <li class="collection-item avatar email-unread">
                <span class="circle indigo darken-1"></span>
                <span class="email-title"> Subject </span>
                <p class="truncate grey-text ultra-small"> Message </p>
                <a href="#!" class="secondary-content email-time"><span class="blue-text ultra-small">Date Recieved</span></a>
              </li>
              <!-- End of Cell Content -->
            </ul>
          </div>
       </div>

I am attempting to append collection items like this through my JavaScript code, but nothing is showing up:

function createHTML(){
   var jsonData = jsonObject;
   for(var i =0; i < jsonData.length; i++){
     $("#mailCollection").append('<li class="collection-item avatar email-unread">' +
       '<span class="circle indigo darken-1"></span>'
       '<span class="email-title">' + jsonData[0]  + '</span>'
       '<p class="truncate grey-text ultra-small">' + jsonData[1] + '</p>'
       '<a href="#!" class="secondary-content email-time"><span class="blue-text ultra-small">' + jsonData[2] + '</span></a>
     </li>')
   }
 }

Answer №1

Your code contains numerous syntax errors related to single and double quotes used in the HTML append function. Below is the corrected code without any syntax errors:

function createHTML(){
   var jsonData = jsonObject;
   for(var i = 0; i < jsonData.length; i++){
     $("#mailCollection").append("<li class='collection-item avatar email-unread'><span class='circle indigo darken-1'></span><span class='email-title'>" + jsonData[0] + "</span><p class='truncate grey-text ultra-small'>" + jsonData[1] + "</p><a href='#!' class='secondary-content email-time'><span class='blue-text ultra-small'>" + jsonData[2] + "</span></a></li>")
   }
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row" id="mailBox">
          <div class="container col s7">
            <div class="collection-header center">
              <h4>Email Box</h4>
            </div>
            <ul class="collection with-header" id="mailCollection">
              <!-- Start: Trying to Dynamically Add These Cells To this view -->
              <li class="collection-item avatar email-unread">
                <span class="circle indigo darken-1"></span>
                <span class="email-title"> Subject </span>
                <p class="truncate grey-text ultra-small"> Message </p>
                <a href="#!" class="secondary-content email-time"><span class="blue-text ultra-small">Date Received</span></a>
              </li>
              <!-- End of Cell Content -->
            </ul>
          </div>
       </div>

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

Ways to maintain image size while zooming out a webpage with CSS

Is there a way to maintain image dimensions when zooming out a page using CSS? Take, for example, fiverr.com. When the page is zoomed out by 25%, And then, when the page is zoomed back to 100% (normal), How can I fix the image dimensions in this situat ...

How to extract just the year from Material-UI's date picker in React

const displayYearOnly = (date) => { const year = date.getFullYear(); console.log(year); }; return ( <div style={{ marginRight: "20px" }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DemoContainer componen ...

BX-Slider allows for the insertion of Prev and Next Arrows in both the Main Div and Inner Divs

I am facing an issue with positioning inner boxes (divs) to the left or right of each slide while adding some text. Although styling them is easy, the problem arises when the Previous and Next arrows appear inside the secondary/inner div, as shown in the a ...

Why is the value of the form's select element always null in jQuery?

I have completed this task multiple times without any issues, but I seem to be facing a problem now. Whenever I make a selection from the dropdown list, the .value always returns null, which is puzzling as I know this should not be the case. Can anyone spo ...

Toggle class in Angular ngMessages based on validity, not just on error

As a beginner with ngMessages, I'm curious to know if there is a $valid counterpart for the $error object. In my exploration of the ngMessages documentation in Angular, I have only encountered discussions about the $error object. <form name="conta ...

Error 404 due to loading Ajax jQuery causing source map issues

When loading jQuery in our app (both web and mobile), we use either the Google CDN or a normal tag. This allows us to correctly load the requested source map (.map) file from the same directory as the jQuery file ('/assets/js'). However, when we ...

Ways to determine if JavaScript array objects overlap

I am working with an array of objects that contain start and end range values. var ranges = [{ start: 1, end: 5 }] My goal is to add a new object to the array without any overlapping with the existing ranges, { start: 6, end: 10 } I need ...

Is jQuery Autocomplete functioning properly on outdated browsers, but not on newer ones?

Here is the JSON data I have for my auto complete feature { "list" : [ { "genericIndicatorId" : 100, "isActive" : false, "maxValue" : null, "minValue" : null, "modificationDate" : 1283904000000, "monotone" : 1, "name":"Abbau", ...

Retrieving data from JSON in Python

Here is a JSON object: { "request": { "id": "123", "url": "/aa/bb/cc", "method": "GET", "timestamp": "2018-08-09T08:41:38.432Z" }, "response": { "status": { "code": 200, "mess ...

Step-by-step guide on positioning mid and bottom text using Bootstrap grid system

After searching and trying various solutions, I am still unable to get the desired output. My goal is to use grids in Bootstrap to set the footer layout with the class "link-footer" positioned at the middle height of the div and the class "footer-copyright ...

How to Use Jquery to Perform Subtraction on Elements

Hello everyone! I am currently working on creating a nutrition label similar to this one: Example I have set up my database and now I am focusing on getting it to work with one element before moving on to the rest. Here is what my database looks like: in ...

Hey there, I was wondering if it's possible to modify the color of the navbar when scrolling on a specific page

After the first 3 pages with a black background and a transparent navbar with white navigation items, I encounter visibility issues when scrolling to the colorful 4th page. Is there a way to change the navbar color on this specific page using ONLY HTML a ...

Exploring a collection of objects in an Angular 2 component

Can someone please assist me in identifying what I am doing wrong or what is missing? I keep getting an undefined value for `this.ack.length`. this._activeChannelService.requestChannelChange(this.selectedchannel.channelName) .subscribe( ...

The focus and blur events for the document in a content editable iframe are not activated by Chrome

As I modify the content of an iframe while it is in focus, I have noticed that this seems to function properly in Firefox. However, I am facing issues as the focus and blur events do not seem to trigger in Google Chrome! var iframe = $('#iframe') ...

Retrieve necessary dependencies in real-time for an Angular project

As I dive into various Angular starter kits, I'm facing a common issue - none of them automatically add the necessary script src for vendor resources like angular formly and bootstrap in the index.html file. This is causing complications with my modul ...

Is it possible to combine numerous -webkit-transition animations in my css code without using keyframes?

I'm experimenting with chaining multiple -webkit-transition animations in my CSS without using keyframes. I understand it's possible to achieve this by calling a keyframe animation, but I prefer to simply overwrite the properties. However, for s ...

Storing the order of jQuery UI Sortable in the WordPress Admin Panel

My goal is to customize the order of taxonomy terms for each individual post in Wordpress. I have created a metabox on the EDIT POST page that contains custom taxonomy terms and made them sortable using JQuery. Here is my setup on the Wordpress backend: ...

ASP updatePanels causing scrollable grid plugin offsetWidth to be undefined

I am attempting to create scrollable gridviews within update panels by utilizing a function that is called in the pageLoad() function LoadScrollPopupOverridesBehavior() { $('.GridViewPopupWithOverride').Scrollable({ ScrollHeight: 350 ...

The step-by-step guide to implementing async/await specifically for a 'for loop'

Is there a way to make 'submitToTheOthers' function run after 'let items = []' has completed, without needing an await within 'submitToTheOthers'? I am considering using await within the for loop in 'submitToTheOthers&apo ...

Changing a particular value within a JSON field in MongoDB using Mongoose on a Linux system

I am currently working on modifying a specific value within a json-type field. The structure of my document schema is as follows: character { name: {type: string}, experience: {type: json} ... } I always ensure that the 'experience&apos ...