Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText>, but now I want to loop through each element in the list. The structure of my array list in javascript looks like this:

<script>    
    topCategory = new Array();
    topCategory.push("one");
    topCategory.push("two");
    topCategory.push("threee");
    topCategory.push("four");
</script> 

I aim to iterate over the topCategory array within an html tag <c:forEach>

For example:

<script>    
topCategory = new Array();
topCategory.push("one");
topCategory.push("two");
topCategory.push("threee");
topCategory.push("four");

After that, I will be looping through this list within a

<table width="100%">          
  <tr>
   <td rowspan="2" width="20%">
     <c:forEach items="#{topCategory}" var="cat">
       <p:commandButton value="#{cat}"/>
              </c:forEach>   
    </td>
  </tr>                         

Answer №1

Apologies for the delayed response, but I hope this information proves helpful for you. It seems like you're looking to iterate through an array in JavaScript and display it as buttons within HTML. To achieve this, you can utilize document.createElement() and appendChild. Here's a sample code snippet:

function getButtonSet(topCategory){
    $('#renderList').empty();
    (function(){
         var t, tt;                        
         category.forEach(renderProductList);
         function renderProductList(element, index, arr) {
            var inputElement = document.createElement("input");                                    
            inputElement.setAttribute("type", "button");
            inputElement.setAttribute("value", element);
            inputElement.setAttribute("name", element);
            var foo = document.getElementById("renderList");
            foo.appendChild(inputElement);
            t = document.createTextNode(element);
          }
     }
}

Within your <td></td>, replace the

<c:forEach></c:forEach>
with
<div id="renderList" ></div>
.

Answer №2

Ensure that your JSP file includes a <c:forEach> loop to iterate through the desired elements.

<script>
topCategory = new Array();
<c:forEach var="val" items="${list}">
topCategory.push("${val}");
</c:forEach>
</script>

This snippet will create the JavaScript code you see in the final HTML, using the data from the ArrayList supplied by your Java action handler. As a result, a JavaScript array will be formed in the user's browser.

Note: Keep in mind that this method only supports basic text values similar to the example provided. Any text with special characters should be properly encoded for JavaScript compatibility.

Answer №3

If you're looking to build your own list and loop through it while generating HTML on the server side, you can achieve that by using:

<c:set var="items" value="${["apple","banana"]}">

For more information, check out this link: Creating Array using JSTL or EL

Answer №4

<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js'> </script>
<script>


function AppViewModel()
{

topCategory = ko.observableArray([]);
    topCategory.push("one");
    topCategory.push("two");
    topCategory.push("threee");
    topCategory.push("four");
}


    
    
ko.applyBindings(AppViewModel);





</script>
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js'></script>

</head>

<body>
The content of the document......
<br>
<ul data-bind="foreach: topCategory">
    <li>
         <b data-bind="text: $data"></b>
    </li>
</ul>

you should definitely give this a try

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

A JSON object received from an AJAX request is either null or empty

I recently deleted a previous question that I had posted because it was no longer relevant and there was another issue to address. The response provided below is very clear, more so than other responses, and I believe it will be beneficial for anyone else ...

Dynamically generating a multidimensional array on a global scale using Java

After successfully creating and implementing the web version of my Ordering System, I am now working on transferring user selections from an App to a Global Multidimensional Array for database storage. The Ordering System involves multiple steps before da ...

The arrival of chat featuring Ajax, long-polling, and support for multiple users has finally

Imagine a site with three modules: "links", "home", and "chat". The "links" and "home" modules are static pages that do not require long polling. However, in the "chat" module, new messages may arrive at any time from other users, requiring an immediate up ...

Dialog component from HeadlessUI doesn't support the Transition feature

Currently working with Next.JS version 14.1.3 I recently integrated the <Dialog> component from HeadlessUI and configured TailwindCSS. However, I encountered an issue where the Modal window doesn't have any transition effects even though I foll ...

Selenium: Uploading a file when the file input element is dynamically inserted into the DOM after the file dialog is displayed

I am facing an issue while working with Selenium and Java: My problem lies in trying to upload a document. I am aware that I need to use sendKeys on the file input field. However, the challenge here is that there is no visible file input field in the DOM. ...

Efficiently navigating a JSON document

In my Java chat bot project, I have implemented a matrix as a knowledge base for responses: String[][] knowledgeBase={ {"hi","hello","howdy","hey"},//input 1; if the user inputs any of these, {"hi","hello","hey"},//output 1; randomly choose be ...

How to locate sub-elements using the @FindBy annotation of the parent element in Selenium/PageFactory?

I am in the process of transitioning my selenium tests to utilize the Page Object Model along with @FindBy. In my current object definitions, I have set up something similar to this: public WebElement objectParent() { return driver.findElement(By.name ...

Discover the simple steps to generating dynamic variables with jQuery!

I am looking to dynamically create jQuery variables based on values in a loop. Here is an example of what I am trying to achieve. array=["student","parent","employee"] $.each(user_types, function( index, value ){ var dynamicType = value + "_type"; // t ...

Refresh database post drag and drop operation

I am seeking a way to update a "state" SQL row after dragging an element between the "DZ", "WT", and "ZK" divs. Below is a snippet of my code: SQL queries: $sql = "select * from tasks where login = '$user_check' AND state = 1"; $sqlDodane = mys ...

Can one transition from using a callback to a returning Promise in order to implement an ErrorFirstCallback strategy?

In Node.js documentation, it is explained that an ErrorFirstCallback is triggered when the referred function fails. Error-first-callbacks in Node.js I have been practicing with this callback pattern and I am curious to know if it is possible to refactor i ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

Prevent a div from being displaced by the transform property once it reaches the window's border

Is it possible to prevent the viewer I created using CSS transform from moving when its borders reach the window borders? Should I consider using a different method instead? If you'd like to see the code, you can check it out here. var x=0, y=0 ...

Adding a disabled internal Style node to the HTML5 DOM: A simple guide

According to this, the style tag can be turned off using the disabled attribute. I attempted the following: <head> <style>body { color: black; }</style> <style disabled>body {color: red; }</style> </head> <bo ...

"Enhancing Collaboration with NextJs Multi-Zones' Unified Header

Currently, I have two applications named admin-shell and delivery-management, both of which are being managed using Multi Zones in NextJs. These applications share a common header with navigation links, but I am encountering difficulties navigating betwee ...

Customizing the display field in an ExtJs Combobox

I am working on a java web application that utilizes an entity class to populate a combobox with ExtJs. The issue I am facing is as follows: Some entries in the displayField may contain html code. To prevent any issues, I used flexjson.HTMLEncoder during ...

I am having trouble with my jQuery wrap function and it is not functioning correctly

I'm having trouble with implementing the jQuery wrap function. (function ($) { $.fn.customWrap = function () { applyWrapper(this); return this; }; function applyWrapper($element) { var $input = $('<input&g ...

There seems to be a problem with the output when trying to display the message "You said ${reply}"

In the following code snippet, vanilla.js is being used with ATOM as the text editor and running on nodejs via terminal: 'use strict'; const Readline = require('readline'); const rl = Readline.createInterface({ input:process.stdin, ...

Tips on rearranging the location of a div element within a directive

I have created a custom directive that displays two divs, Div1 and Div2, with a splitter in the middle: Splitter Image Now, I am looking for a way to swap the positions of these two divs dynamically using an Angular directive. I thought about using ng-swi ...

VARIABLE_NAME isn't functioning properly on the window

The code window.VARIABLE_NAME is not functioning properly and is causing the following error. Can you please provide assistance? Uncaught SyntaxError: Unexpected token. This is the code I have written: var window.testing ...

Notify when the focus is solely on the text box

How can I display an alert only when the focus is on a text box? Currently, I am getting an alert whenever I skip the text box or click anywhere on the page. The alert even appears when I open a new tab. Is there a way to fix this issue? Thank you for your ...