What is the correct way to incorporate a for loop within a script tag in EJS?

When attempting to create a chart using chart.js, I encountered an issue.

In order to retrieve my data, I attempted to use ejs tags.

For example, within the ejs input HTML below, everything worked smoothly.

<p>date: <%= today %></p>
  <p>temperature: <%= data[data.length-1].temperature %>℃</p>

  <h1>5 days average temperature</h1>

  <ul>
    <% for(var i = 0; i < 5; i++) {(function (j) {%>
      <li><%= dateList[j] %>></li>
      <ul><li><%= avgLocTmpList[i] %></li></ul>
    <%(i);} %>
</ul>

However, when working with chart.js, I had to use ejs tags in a different manner like demonstrated below.

<script>
        var temper0 = '<%= data[0].temperature%>';
        tempList.push(temper0);
        var temper1 = '<%= data[1].temperature%>';
        tempList.push(temper1);
        var temper2 = '<%= data[2].temperature%>';
        tempList.push(temper2);
</script>

I was able to successfully obtain data[0].temperature using this method.

However, I wished to incorporate a for loop within the script tag, like shown below:

<% for(var i = 0; i < 5; i++) {
<%= data[i].temperature %>
<% }%>

Unfortunately, I faced difficulties in implementing this for loop inside the script tag. Are there any suggestions or alternative methods for achieving this?

Thank you in advance.

Answer №1

I encountered a similar situation before and found success using this code within script tags! Give it a try and see if it works for you.

<script type="text/javascript">
   <% data.forEach(function (d) { %>
       console.log("<%= d %>"); // or any other action you wish to perform.    
   <% }) %>
 </script>

Additionally, I noticed there is an error in the loop code you provided. Make sure to pay attention to opening and closing ejs tags. The first line is missing a closing ejs tag.

<% for(var i = 0; i < 5; i++) {
<%= data[i].temperature %>
<% }%>

Be sure to use:

<% for(var i = 0; i < 5; i++) { %>

Answer №2

I attempted to retrieve property images from my database using the following method:

<script>
     let retrievedData = JSON.parse('<%-JSON.stringify(property)%>')
     let imageDataArray= [];
              for (var j = 0; j < retrievedData.length; j++) {
                let img = retrievedData[j].image_name
                imageDataArray.push({
                  id: j, src: '/uploads/properties/' + img
                })
    
              }
</script>

Answer №3

In my MongoDB database, I needed to calculate the total sum of prices for items in a customer's shopping cart. After trying various examples and running into red underlines in the code, I realized that it was essential to properly quote the code when using variables from the server side. This not only eliminated the red underlines but also made the code look clean and error-free.

 <script>
    let prices = []
    let pricex;
    let sum = 0;
 " <% for (let i = 0; i < products.userCart.length; i++) { %>"

        pricex = "<%= (products.userCart[i].quantity * products.userCart[i].price) %>";

        prices.push(pricex);
    
   " <%    } %>"

    for (let i = 0; i < prices.length; i++) {
            sum = sum + parseInt(prices[i]);
        
    }

    console.log(sum);
</script>

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

Avoid running getStaticPaths for a specific locale

Is there a way to prevent Next.js getStaticPaths from generating static pages for a specific locale? In my Next.js configuration: i18n: { locales: ['default', 'en', 'hu', 'de', 'cz', 'eu', ...

JavaScript function that allows jQuery .val() to replace trailing decimal points

Currently, I am working on restricting the input allowed in a numeric text field. My approach involves checking the length of the input field's value, and if it is greater than or equal to the specified maxlength attribute, no further input is accepte ...

Invoke the mounted lifecycle once more

At the moment, my table is set up to use the v-for directive to populate the data: <table v-for="(data, idx) in dataset" :key="idx"> </table> Following that, I have two buttons that perform actions in the database, and I wa ...

The Array.splice() method in Angular JS may result in undefined elements

Hey there! Currently, I am tackling the task of manipulating my Array by inserting objects at index 0 with the push method and eliminating items using splice. As per my understanding, when you splice an item from an array, it should not result in an &apos ...

Property list is incomplete and requires an "after" parameter

This particular piece of code is generating the following error message: missing : after property list exactly where the error comment is placed. $("#jquery_jplayer_1-<?php echo $key.'-'.$j; ?>").jPlayer({ ready: function () { ...

Exploring VueJS's capability to monitor the changes of two different

If I have two data properties: data() { return { a: false, b: false, } } Is there a way to trigger a specific task when both a and b are set to true simultaneously using Vue's watch method? ...

What causes an object to declare itself as undefined only in the event that I attempt to access one of its properties?

Check out this snippet of code: req.Course.find({}).populate('students', 'username firstName lastName registered').populate('teacher', 'image mID firstName lastName').sort({title: 1}).exec(function(err, courses){ ...

Apply the cursor property to the audio element and set it as a pointer

I have a question: how can I apply a cursor style to my <audio> controls? When I try to add them using CSS, the cursor only appears around the controls and not directly on the controls themselves. Below is the code snippet: <audio class="_audio" ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

There seems to be an issue with the performance of Google script .setFormula when used in conjunction with the

Hello everyone, I have written a script that inserts formulas in a specific range and set up a trigger for it to run between 01:00 and 02:00 AM. The purpose is to subscribe the values with the formulas and then paste the resulting values. However, I am fac ...

Guide on integrating a JavaScript file for user scripts into a Chrome extension

Lately, I've been working on creating user scripts for Chrome that can operate without relying on Tampermonkey. Recently, I integrated a third-party extension (a userscript js) into my Chrome extensions: // ==UserScript== // @name "job changer" ...

Loading an empty CSS file in Node.js

Just starting out with node.js, and I could really use some help with a small css and image issue that I'm facing. I've streamlined my html and .js for clarity. Despite trying everything, the css and image just won't load. My form and server ...

The getter method in the Vuex store object seems to be returning varying values when accessing nested properties

Currently, my Vuex store is being used to store a user object. This code snippet is a getter function for the user object: getters: { user: (state) => state, isAuthenticated: state => { console.log("user object", state); ...

The children's className attribute can impact the parent element

As I work on creating a card object, I envision it with the className .card that is styled in CSS as follows: .card img{position:absolute; width:150px; height:160px} I want only the images inside my div to overlap each other while not affecting the divs ...

Downsampling an enormous JSON array using Haskell

Trying to work with a massive Json file without loading it entirely into memory can be quite the challenge. The structure of the file is simply a large array with various elements inside, and I am looking to randomly reduce the number of elements in the ar ...

Speeding up the loading time of my background images

body { background: url(http://leona-anderson.com/wp-content/uploads/2014/10/finalbackgroundMain.png) fixed; background-size:100% auto; } I have unique background images on each of my sites, but they are large in size and take some time to load due to bein ...

Issue with sending array as parameter in ajax call in Laravel

I am currently encountering an issue while attempting to pass an array through an AJAX request. <input type="text" name="item_name[]"> <input type="text" name="address"> $(document).on('click', '#save_info', function () { ...

Struggling with lag in MaterialUI TextFields? Discover tips for boosting performance with forms containing numerous inputs

Having some trouble with Textfield in my MateriaUI project. The form I created has multiple inputs and it's a bit slow when typing or deleting values within the fields. Interestingly, there is no lag in components with fewer inputs. UPDATE: It appear ...

the process of configuring date string for x-axis labels in chartjs

I recently created a time scale chart using chart.js. However, I now want to change the labels in my data array to be in the format of 01-02-2017, 02-06-2017 instead of "4 February 2017", "9 February 2017" and so on. Below is my code: var aR = null; va ...

Using Python to decrypt JSON nested within JSON files

Trying to parse this JSON in Python raises the following error: "foo": { "foo_id": "1", "foo_name": "i", "foo_client_id": "2", "foo_c ...