Using a ForEach iteration to loop through a table in C# and jQuery

My generated table structure is as follows:

<div class="row">
<div class="col-md-12">
    <div id="calendar"></div>
    <table id="report" class="table">
        <thead>
            <tr>
                <th>Event</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody />
    </table>
</div>

The table content is dynamically populated via javascript:

var tableDetails = [
    data.title,
    $.fullCalendar.formatDate(startDate, "dd MMMM yyyy"),
    $.fullCalendar.formatDate(endDate, "dd MMMM yyyy"),
    data.published ? "Published" : "Not Published"
];

var row = $("<tr></tr>");

for (var i = 0; i < tableDetails.length; i++) {
    row.append($("<td></td>").text(tableDetails[i]));
}

$("table#report > tbody:last").append(row);

I am exploring methods to iterate through the table rows using a foreach loop in order to retrieve a list of all Events for passing to a controller. A list/array of strings would suffice, as EventIds can be added to uniquely identify each event within the table.

Answer №1

Here is a concise version...

$(".table-data tbody tr").each(function() {
    // perform a task with $(this) representing the current row
});

Answer №2

Easy jQuery code to loop through each row and cell : (Excludes TH Cells)

    $('#report tr').each(function() {
        //perform action on row...
        $(this).find('td').each(function() {
            //perform action on cell...
        });
    });

Answer №3

Is there a way to utilize a foreach loop to iterate through the rows of a table, in order to create a List containing all the Events that can then be passed to a controller?

If your requirement is simply an array of a specific property (such as the event name) from each object, this code snippet will fulfill that need. Otherwise, the alternative answers shared here demonstrate the proper manner of iterating through each row and cell.

var list = $('#report > tbody > tr').map(function () {
    return $(this).find('td:eq(0)').text();
}).get();

For instance, if you have three events, it will result in

list == ["event 1 name", "event 2 name", "event 3 name"];

Naturally, you have the flexibility to adjust the return statement above according to the property of interest, such as $(this).attr('id')

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

Troubleshooting issue with parsing MySQL data in HTML table using Node.js

Seeking Assistance! I am currently in the process of developing a node file that displays data from MySQL on an HTML page with a search bar. My issue is that sometimes when I run the code, enter something into the search bar and hit the button, it works s ...

The Jquery function appears to be malfunctioning, however, no errors are being reported

I am trying to make my <h2> element move to the center of the page with a click event. However, I am currently facing an issue where it does not respond as expected. My goal is for the element to move to the center when clicked once and return to its ...

Is there a way to use jQuery to automatically scroll to the most recent ID on a

I wish to create a feature where clicking the "load more" button will automatically scroll the content to the last id. Interesting concept, right? For instance: $(document).ready(function(){ $("#loadmorebutton").click(function (){ $('#lo ...

What is the process for making an Ajax request in Rails?

I'm attempting to send a variable through jQuery using the POST method, saving it in a controller, and then utilizing that same variable in Rails HTML to query a table. It seems like the variable isn't being passed to the controller. jQuery: v ...

After two HTML injections, Javascript ceases to function properly

I am in the process of developing a chat feature for my website. The layout includes a conversation section on the left and a list of users on the right. When a user's div is clicked, their ID is transmitted to the Django back end. Subsequently, full ...

A guide on converting JSON to FHIR using C#

I'm in need of assistance with JSON and FHIR as I am unfamiliar with them. Specifically, I have a request to a FHIR server that retrieves a medication dispense object. The result of the request is contained within this string: {"resourceType" ...

Center an absolutely positioned div using CSS

What is the best way to position an absolute div at the center? <div class="photoFrame">minimum width of 600px, positioned absolutely</div> jQuery var screenWidth = $(window).width(); $('.photoFrame').css({'margin-left': ...

Switching visual representation that appears upon clicking the dropdown menu

Issue with Duplicating Dropdown and Image Change const image = document.querySelector('.item__img'); const checkbox = document.querySelectorAll('.imgOption'); function handleChange() { let imgsrc = this.getAttribute("data-value ...

How to dynamically insert elements into the HTML page using Angular

When my page first loads, it looks like this <body> <div class="col-md-12" id="dataPanes"> <div class="row dataPane"> Chunk of html elements </div> </div> <div class"col-md-12 text-right"> <input type="butt ...

Tips for handling attributes of an HTML element when the HTML content is stored within a variable

Here is a sample HTML code stored in a variable: var sHtml='' sHtml='<div class="diagnostic_picture"><img src="test1.gif" /></div>'; sHtml=sHtml + '<div class="diagnostic_picture"><img src="test2.gif" /& ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...

Once it hits the fourth tab, it must not cycle back to the first one

Hi there, I'm new to JavaScript I noticed that when I click the left and right arrows, the tabs circle back to the beginning However, I would like the circle to stop. When it reaches the fourth tab, it should not go back to the first. This should also ...

Utilize the ForEach method on an object obtained through a jQuery ajax request

I have encountered an issue where I am unable to retrieve values from a collection passed through AJAX in my webmethod using a foreach procedure. The collection variable in question is var Leave = { "Date": [], "Half": [] }; When passing Leave to the webme ...

Tips for adding a form input field into a table structure

I have successfully displayed all student names in a table format using AJAX. Now, I would like to connect a form input field to each student so that I can input their marks and save it in the database. How can I go about achieving this? Below is the code ...

Navigating links with Jinja using jQuery and AJAX

A series of items from the workshop variable are being shown by iterating through each item in a sequence. {% for car in workshop %} <div id="newDiv" > <a class="carsInWorkshop" title="{{car.carId}}" href="./getPriceforCar/{{car.carId}}"& ...

Building an expandable vertical dropdown with Bootstrap that opens with a click

My goal is to design a vertical menu that expands when clicked, revealing 3 links for each item. I currently have the following setup: This is the initial layout: After clicking all items: The code I've implemented so far looks like this: <!DOC ...

What is the best way to choose the ul list item option using Selenium and C#?

Is there a way to select an item from a ul list using Selenium with C# on a web page? While I can access other controls by their IDs, the select control is giving me trouble. Here's what I have tried: https://i.stack.imgur.com/3u6dm.png This is my a ...

Encountering an issue with jQuery ajax when attempting to make a post

I am having trouble making a rest service call from JQuery ajax using the POST method. Below is my code: <!DOCTYPE html> <html> <head> <script src="lib/js/jquery/jquery-1.7.2.min.js"></script> </head> <body> & ...

Prevent sound from continuing to play when a different DIV is selected

I require help in developing a compact soundboard for my project to deepen my understanding of jQuery. The objective is to halt and reset the audio from the current file when another div is clicked, prompting the playback of its corresponding audio file in ...

In what ways can I enhance and visually improve JSON data using a jquery/javascript plugin?

My current project requires me to display JSON data received from the backend in a textarea. However, the data comes unformatted and not validated. Now I'm facing two main challenges: 1) How can I beautify the JSON content in the textarea? 2) How can ...