Search code examples
jquerymultiplicationcalc

jQuery multiply only values that are not hidden


I am pondering how you would add up all values of inputs with specific names via jQuery if their container Div is set to display block.

Something link if ($('#product_' + this.alt).css('display','block')) {

Then it needs to add up .each with fetching the input something like this.

$('#product_price_total_PRI_' + this.alt).val

Any ideas on how I would put all of that together?

Edit:

Obviously I should clarify. Encased in the alt tag of multiple checkboxes and radio buttons is an ID that corresponds to the IDs of hidden containers and fields. Therefore the combination of buttons and checkboxes that are checked determines what hidden areas are visible as seen here.

function product_analysis_global() {
$(':checked').each(function(){
    $('#product_' + this.alt).css('display','block');
    $('#product_quantity_PRI_' + this.alt).val(this.value);
    var quantity = $('#product_quantity_PRI_' + this.alt).val();
    var price = $('#product_price_PRI_' + this.alt).val();
    var duration = $('#product_duration_PRI_' + this.alt).val();
    var dives = $('#product_dives_PRI_' + this.alt).val();
    var hire = $('#product_quantity_PRI_' + this.alt).val();

    $('#product_price_total_PRI_' + this.alt).val(price * quantity);
    $('#product_duration_total_PRI_' + this.alt).val(duration * quantity);
    $('#product_dives_total_PRI_' + this.alt).val(dives * quantity);
    $('#product_hire_total_PRI_' + this.alt).val(hire * quantity);

}); 

What I need is a field called 'GT_grand_total' to be the sum of all fields that area '#product_price_total_PRI_' + this.alt).val()' only if their panel '#product_' + this.alt is visible.


Solution

  • As per your requirement

    var arr = $("div[id*='product_']").not(":hidden").map(function(){
      return $(this).find("input[id*='product_price_total_PRI_']").val();
    }).get(); 
    
    
    
    var total = 0;
    $.each(arr,function() {
        total += parseInt(this);
    });
    alert(total);
    

    Or for total

    var total = eval(arr.join('+'));
    
    alert(total);
    

    Working example

    http://jsfiddle.net/wB5Hh/2/