Utilizing arrays in ejs with HTML elements

I have an array that looks like this:

["Item1", "Item2", "Item3"]

I want to utilize this array to iterate through the items and populate the following HTML format:

<option data-img-src=ITEM 1 value="1"></option>
<option data-img-src=ITEM 2 value="2"></option>
<option data-img-src=ITEM 3 value="3"></option>

In addition, I also need to extract the value for each item.

For example, the first one would be value="1" and so on incrementing by one.

Answer №1


Incorporating JavaScript into your code allows you to dynamically generate and add new elements to the HTML document.

var items = ["Item1","Item2","Item3"];
for (var j = 0; j < items.length; j++) {
    newItem = document.createElement("LI");
    newItem.setAttribute('data-img-src',items[j]);
    newItem.setAttribute('value',j+1);
    document.body.appendChild(newItem);
}

Answer №2

Using EJS, we have an array called obj with values like "Object1", "Object2", and "Object3".

We can utilize a forEach loop to iterate through the objects.

<% obj.forEach(function(val,index) { %>
                 <option data-img-src=<%= val %> value=<%= (index+1) %>></option>
 <% }); %>

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

Images are failing to show up in the iPhone design

Encountering issues with displaying images on an iPhone? You can replicate the problem by minimizing your browser window horizontally. Here is a link showcasing the problem: here. To temporarily fix this, try zooming out the browser (Ctrl+-). You can see a ...

Endless Keycloak redirection loop

We have integrated Keycloak 2.3.0.Final into our system and are utilizing the Javascript adapter located at /auth/js/keycloak.js. Our application, built using React+Redux, encounters an issue during the authentication process outlined in the documentation. ...

Error encountered: Segmentation violation (core dumped) during execution of C program (transferring text to array

A challenge I'm facing involves writing code that captures input from the command line (a redirected text file) and stores the data into an array in C. Unfortunately, every time I run the program, it gives me a segmentation fault (core dumped) error m ...

Concealing Content within an Accordion

Looking for some guidance on setting up a mobile version of my product image with hover features. Currently using tooltips on desktop and planning to use a modified accordion on mobile, but struggling to make progress. Customized some JS to toggle an acco ...

Problem with white screen in Cocos2d-html5

I'm experiencing an issue with my cocos2d html5 game on the Tizen platform. While it runs perfectly on PC and all browsers without any errors, on Tizen it only displays a white screen. It seems like the update loop is functioning correctly, but there ...

Verify whether the initial value is distinct from the subsequent one using AJAX

I'm currently working on a project where I need to compare the first value received from an AJAX call to the subsequent values. However, I seem to be stuck and unable to figure out how to achieve this. Every 5 seconds, I am checking the follower count ...

Display the invoice bill using text in a Vue component

Hello, I am looking to print an invoice that resembles the one shown in this picture https://i.sstatic.net/6mzwe.jpg However, when I try to print it, I get a different output with some additional elements https://i.sstatic.net/uaKZC.jpg I am using vue. ...

Unable to initialize an array in a C# POST request

var resultHttpPost = ZennoPoster.HttpPost("http://box.chomikuj.pl/services/ChomikBoxService.svc", "<?xml version='1.0' encoding='UTF-8'?><s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s= ...

Implementing pagination in Webgrid using AJAX post method

I've developed this JavaScript code: function PartialViewLoad() { $.ajaxSetup({ cache: false }); $.ajax({ url: "/ControllerAlpha/MethodBeta", type: "GET", dataType: "html", data: { s ...

Mastering the use of JArrays in the copy activity of Azure Data Factory

Currently, I am facing an issue with my copy activity where I am using a MongoDB JSON file as the source data and attempting to sink it into an Azure SQL Database. The problem arises from the fact that my JSON file consists of an array of email addresses. ...

What is the most effective way to loop and render elements within JSX?

Trying to achieve this functionality: import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = {"0": "aaaaa"}; return ( ...

Is there a way to trigger a Python script from a webpage using a function?

As someone who is new to html and webpages, particularly coming from an embedded engineering background, I have been tasked with automating certain processes that require a python script to run on a Raspberry Pi upon clicking a button on the webpage. I ha ...

Detecting unutilized space in a collection of divs with varying sizes using JavaScript and CSS

To better understand my issue, I created a StackBlitz demo: https://stackblitz.com/edit/angular-aqmahw?file=src/app/tiles-example.css Screenshot My tiles can have four different widths (25%, 50%, 75%, 100%). The tiles must fit on only two lines, so if a ...

Is there a way to design a CSS layout that automatically adjusts text wrapping based on the size of the page and columns?

I am attempting to design a CSS page that mimics the appearance of an aged newspaper. The focus is on ensuring that the page is responsive, with a single column of text on smaller devices. However, the main issue I need help with lies elsewhere. For larg ...

What is the most effective way to accurately identify the mobile platform of a user using JavaScript?

I need to determine whether a user has accessed the application through a browser on Android or iOS. The company would like to display slightly different content depending on the platform. While I am aware that navigator.platform can be used for this pur ...

Is there a way to link a React component with cucumber.js?

I am looking to integrate React with Cucumberjs by creating a Word class that connects the App component. import { setWorldConstructor } from 'cucumber' import {render } from '@testing-library/react' import React from 'rea ...

When implementing getStaticProps and getStaticPaths in a dynamic route, a 404 error page is displayed

As someone new to Next.js, I decided to delve into creating a basic news website where I could access articles through this specific route: /[category]/[article] The directory structure of pages is organized as follows: _pages __[category] ____index.jsx ...

Internal Server Error 500: Issue with Ajax/JavaScript

I have reviewed some previous posts, but unfortunately, they did not provide the help I need. When my program runs and I click on a button to trigger a JavaScript function, nothing happens - there is no response. In the Chrome debugger under the network ta ...

Exploring Data Retrieval and Presentation in React JS

I have successfully stored data in my database. However, I am curious about how to display/render the retrieved data on my screen after making a fetch request. When adding data, I can easily push it to render on my page. But my question is, after running ...

What is the best way to activate an event listener only after a button has been clicked?

Currently, I am developing a game that includes a timer and an event listener that notifies the user not to switch tabs. However, I am facing an issue where the event listener triggers before the game's start button is clicked. Is there a way in JavaS ...