Jeepstone
Jeepstone

Reputation: 2601

Find td value in table using drop down filtering in jQuery

http://medfor.petersenuploads.co.uk/product.php/698/2/clear-ps-honey-jar-with-metal-screw-cap

There is currently a set of dropdowns in the middle of the screen and also a tab (Full Product List). If you click one of the products in the full product list, it updates the dropdown lists. This includes a hidden field (Items per case)

What I want to do, is grab the value of Items Per Case (from the table) based on the 3 selected dropdowns. For instance:

Select 100ml, Sterile R, No label - this matches the 2nd row in the table. I want to grab the value of 'Items per case' from the table so that I can set the hidden dropdown (items per case) and get the correct product to add to the basket.

The code that does this is in script.js

// Handles changing any drop downs in the product selection area and updates the choosen item based on label names and field values.
$('.product-options select').change(function() {
    $('p.selection-item').text("");
    $('#selection-name').text($('header>h1').text());
    $('.product-options select').each(function (i) {
        $('p.selection-item').append($("label[for='"+$(this).attr("id")+"']").text() + " " + $('option:selected', this).text(), "<br />");

        var tableRow = $(".product-table td").filter(function() {
            return $(this).text() == "50";
            //Needs to match against all drop down values
        }).closest("tr");
        console.log(tableRow);
    });
    $('div.product-selection h2').removeClass('noshow');
    $('div.product-selection p').removeClass('noshow');
    recalcPrice($('#pid').val());
});

I need to filter the table to get a single row out and then grab the value of the penultimate column. How can I do this?

Upvotes: 0

Views: 1924

Answers (1)

JoeFletch
JoeFletch

Reputation: 3970

Assuming that the columns / td placement is static, you can do the following.

var tableRow = $(".product-table tbody tr").filter(function() {
            var
                cap = $("#capacity :selected").text(),
                ster = $("#sterility :selected").text(),
                lbl = $("#labeltype :selected").text();
            return $(this).find("td").eq(0).text() == cap && $(this).find("td").eq(1).text() == ster && $(this).find("td").eq(2).text() == lbl
        });

If the columns / td placement is dynamic, you can do the following.

var tableRow = $(".product-table tbody tr").filter(function() {
            var arr = [],
                cap = $("#capacity :selected").text(),
                ster = $("#sterility :selected").text(),
                lbl = $("#labeltype :selected").text();
            $.each($(this).find("td"), function(){
               arr.push($(this).text());//there was a parenthesis missing here.
            });
            return $.inArray(cap, arr) != -1 && $.inArray(ster, arr) != -1 && $.inArray(lbl, arr) != -1;
        });

Upvotes: 1

Related Questions