Discovering data in individual tr elements within a table with jQuery by utilizing .text()

I'm currently working on a project where I need to separate the three table rows within a dynamically generated table. My goal is to have jQuery treat each row individually in order to extract specific values like price and SKU. You can see an example of what I'm trying to achieve in the fiddle link provided below.

Since all the rows have the same classes for each product, my approach involves defining each tr as a unique variant. From there, I can search through them using .text() to retrieve the desired values.

Here's a snippet of the code (jsfiddle link included):

jQuery:


        var firstprice = $('#checkout .orderitems table.wizrtable tbody tr td.priceeach').text().replace(/\u00A3/g, '');
        // Price of a single product in checkout

        var amountofproducts = $('#checkout .wizrtable tbody tr').length;
        // Number of table rows in the checkout structure

        $(document).ready(function () {
            if (+amountofproducts >= 4 && +amountofproducts <= 8) {
                // Define unit price
                var firstrow = $('.wizrtable').closest('table').children('tr:first');
                var firstprice = $(firstrow.find('#checkout .orderitems table.wizrtable tbody tr td.priceeach')).text().replace(/\u00A3/g, '');
                
                var secondrow = $('.wizrtable').closest('table').children('tr:eq(1)');
                var secondprice = $(secondrow.find('#checkout .orderitems table.wizrtable tbody tr td.priceeach')).text().replace(/\u00A3/g, '');

                var thirdrow = $('.wizrtable').closest('table').children('tr:eq(2)');
                var thirdprice = $(thirdrow.find('#checkout .orderitems table.wizrtable tbody tr td.priceeach')).text().replace(/\u00A3/g, '');

                // Define item IDs for each product
                var firstSKU = $(firstrow.find('#checkout .orderitems table.wizrtable tbody .name .sku')).text().replace("Product Code: ", "");
                var secondSKU = $(secondrow.find('#checkout .orderitems table.wizrtable tbody .name .sku')).text().replace("Product Code: ", "");
                var thirdSKU = $(thirdrow.find('#checkout .orderitems table.wizrtable tbody .name .sku')).text().replace("Product Code: ", "");

                // Inject html div with result
                var Firstprodprice = jQuery("FirstprodPrice").text(firstprice);
            }
        });
    

JS Fiddle Link: http://jsfiddle.net/hslincoln/7HXBQ/10/

Any advice or suggestions?

Answer №1

Your previous code on jsfiddle was almost correct. I have made some updates and corrections: http://jsfiddle.net/Ht5nm/2/.

Here are the corrections:

var secondrow = $('.wizrtable').children('tr:second');

The :second pseudo selector does not exist. Use :nth-child(n) instead. Also, .children() only works on immediate children, so you need to include tbody in the selector.

var secondrow = $('.wizrtable tbody').children('tr:nth-child(2)');

I am not sure why there were + signs before the variables.

if(+amountofproducts >= 4 && +amountofproducts <= 8)
. However, this variable depends on the number of table rows, so the if statement may not work for your jsfiddle example.

In addition, I had to add #checkout in my jsfiddle for expected code execution that was missing in your original version.

Your current approach may not be scalable for handling multiple table rows. It would be better to dynamically manage rows rather than using firstrow, secondrow, thirdrow, etc.

var Firstprodprice = jQuery("FirstprodPrice").text(firstprice);

This line does not require assigning a variable. In addition, the element with the class 'Firstprodprice' should have a lowercase 'p' in price. Therefore, this line would not have any effect.

Answer №2

Your HTML contains some handy div elements that eliminate the need for regular expressions. Although untested, a possible solution could be...

$('#wizrtable tr').each( function( index,element)  {
   var sku = $(element).find( 'div[title="pid"]').text();
   var qty = $(element).find( 'div[title="qty"]').text();
   var price = $(element).find( 'div[title="tv"]').text();
});

Answer №3

Aside from generating the output, this process eliminates the need to manually determine the number of products in the table and scrapes data for the entire table....

$(document).ready(function () {
// Define unit price
var tbody = $('.wizrtable tbody');
var prices = $(tbody).find('.priceeach');
var skus = $(tbody).find('.sku');
var quants = $(tbody).find('.quantity');
var product = [];

$(prices).each(function (idx) {
    product[idx] = {
        price: $(this).text().replace(/\u00A3/g, '')
    }
});
// END: Define unit price

// Assign item IDs to each product
$(skus).each(function (idx) {
    product[idx].sku = $(this).text().replace("Product Code:", "");
});

$(quants).each(function (idx) {
    product[idx].qty = $(this).text();
});
// END: Assign item IDs to each product

// Populate html div with results
// Product 1
$(".Firstprodprice").text(product[0].price);
$(".FirstSKU").text(product[0].sku);
$(".FirstQTY").text(product[0].qty);
// Product 2
$(".Secondprodprice").text(product[1].price);
$(".SecondSKU").text(product[1].sku);
$(".SecondQTY").text(product[1].qty);
// Product 3
$(".Thirdprodprice").text(product[2].price);
$(".ThirdSKU").text(product[2].sku);
$(".ThirdQTY").text(product[2].price);
});

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

Using Backbone.js to Retrieve Data from the Server and Bind it to a Model

Having recently delved into Backbone.js, I found this informative tutorial quite helpful in getting started. Now, I am looking to take things a step further by fetching data from the server instead of hardcoding values in JavaScript as demonstrated in the ...

Can you explain the distinction between using .hover and :hover?

Recently, I came across some CSS code that was written by someone else and it contained the following: li.hover, li:hover { } This made me curious - is there a distinction between .hover and :hover in CSS? Could it be possible that certain browsers inte ...

Having trouble retrieving JSON data from an AJAX request and showing it in an HTML page

Having some trouble with utilizing the New York Times bestseller list API to showcase the current top 20 in html. I've successfully retrieved the data using ajax (confirmed through developer tools) but hit a roadblock when attempting to display it on ...

Using Jquery to attach an event to a particular div which is part of a group of divs sharing

I am trying to implement a mouseup event on a series of divs that, when clicked, will reveal a child div ('menu'). All the parent divs have the same class. Here is an example: <div class="container"> <div class="menu"><p>Text ...

Utilize the CSS property font-family to inherit styles for headings

Is it possible to use a different font family for headings than the one used in the body text while still maintaining a consistent look across all heading levels? One way to achieve this is by specifying the font family for each heading level individually ...

Tips for avoiding content appearing beneath overlapping elements

I am facing an issue with a hero image that has an overlapping box. I want to add content below the box but it ends up appearing behind the box. How can I ensure that the content shows below the box while maintaining responsiveness? .shell { display: ...

displaying only the date in bootstrap-datetimepicker

I am currently utilizing the repository created by smalot, and my intention is to choose and display dates only (while in other instances I showcase both date and time, hence utilizing this repository). Although I have succeeded in selecting dates only, th ...

The inclusion of individual CSS files in a TypeScript React project does not have any effect

My issue involves creating a new react project with typescript and adding a custom component with a separate CSS file for styling. The folder structure is as follows: https://i.sstatic.net/UNtEP.png In the Header.css file, I have defined a class: .mainHe ...

Changing from using GET to employing POST

My current Ajax request function is as follows: // JavaScript function myFunc(pid) { $.ajax({ type : "GET", url : "testback.php", contentType : "application/json; charset=utf-8", dataType : "json", data : { ...

Tips for automatically scrolling images horizontally in responsive layouts

Recently, I've been working on a website called . On the homepage, my portfolio images are arranged in a grid format using the <li> tag. I'm looking to align them side by side and have them scroll horizontally automatically, preferably with ...

Prevent any further dissemination if I continue typing repeatedly

As I develop a custom search engine for a website, the search functionality operates through AJAX on keyup events. This means that when you begin typing (assuming you type more than two characters and after any leading or trailing spaces are removed), an A ...

The overflow hidden function does not seem to be fully functional on the iPad

Struggling to prevent body scrolling when a modal pop-up appears? I've tried setting the body overflow to hidden when opening the modal and resetting it when closing, which worked fine on desktop browsers. However, mobile devices like iPod/iPhone pose ...

Using cakePHP to submit a form using ajax

While submitting a form using ajax and attempting to return a json response, I encountered an issue of receiving a missing view error. Adding autoResponder=false resulted in no response at all. This is happening while working with cakephp 2.5 In the same ...

Move the contents of a div to the right side

One of the issues I am facing is with aligning replies to comments correctly in my comment section. The replies are not aligning properly with the parent comment and it's causing a display problem. Link to JSFiddle for reference Here is the CSS code ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...

Enhancing Tabulator tooltips with custom CSS styles

Is there a way to style the tooltips that appear when hovering over cells in my Tabulator table? When I set tooltips:true, Tabulator adds a title tag, but applying CSS inline has been tricky. So far, I have tried: div[title]:hover:after { content:attr( ...

What is the best method for passing parameters from HTML to AJAX within code?

My project involves working with Flask, HTML, and Ajax. Here is the HTML code snippet: <script type=text/javascript> $(function() { $('a#calculate').bind('click', function() { $.getJSON('/_add_numbers&ap ...

Utilizing Jquery for comparing and retrieving string arrays

Hey there! I'm currently working on a jQuery application and I'm facing an issue with comparing two arrays. Here is an example: FirstArray=["Mike","Jack"]; SecondArray=["Mike","Jack","Andy","Cruz"]; I want to find out which strings are common i ...

The HTML element <a> can have both a href attribute and a onclick attribute

I'm currently facing a challenge with my project - I am trying to create a submenu that includes all sub-pages within a single HTML file. However, whenever I attempt to use both href and onclick, the functionality fails to work as intended. The only ...

Executing AJAX function via a dropdown button

Utilizing a jquery-based dropdown menu from here. The dropdown is added to an existing button triggering an AJAX call that removes a row from the screen. The goal is to execute the AJAX call when any option in the dropdown is selected, instead of using th ...