Lynx
Lynx

Reputation: 1482

Getting price from multiple select boxes

I have a simple jquery script that I am using to build an appointment system for a client. The data-price represents the actual price of the services rendered. I need to be able to combine that result with the other drop-downs rather then just take whatever data-price is selected

jQuery

$("select").change(function(){
   var price = parseFloat($(this).find("option:selected").data("price"));
   if(isNaN(price))
       price = 0;
   var currPrice = parseFloat($("strong").data("price"));
   $("strong").text('$ ' + currPrice + price );
})

Relevant HTML (using Laravel 4 blade template to call database table)

<div id="rm_clean" class="tab-pane fade in active">
       Areas:<br />
   <select name="rooms"> 
        <option value="" selected="selected">0</option>
         @foreach ($room as $rooms)
         <option data-price="{{ $rooms->pr_clean }}" value='{{ $rooms->room  }}'>{{ $rooms->room  }}</option>
         @endforeach
    </select>
</div>
<div id="rm_deodorize" class="tab-pane fade">
       Deodorizer:<br />
   <select name="pr_deodorizer"> 
        <option value=''>0</option>
         @foreach ($room as $rooms)
            <option data-price="{{ $rooms->pr_deodorizer }}" value='{{ $rooms->pr_deodorizer  }}'>{{ $rooms->room  }}</option>
         @endforeach
    </select>
</div>
<div id="rm_protectent" class="tab-pane fade">
        Protectant:<br />
    <select name="pr_protectant"> 
        <option value=''>0</option>
         @foreach ($room as $rooms)
            <option data-price="{{ $rooms->pr_protectant }}" value='{{ $rooms->pr_protectant  }}'>{{ $rooms->room  }}</option>
         @endforeach
    </select>
</div>
<div id="rm_sanitizer" class="tab-pane fade">
        Sanitizer:<br />
    <select name="pr_sanitizer"> 
        <option value=''>0</option>
         @foreach ($room as $rooms)
            <option  value='{{ $rooms->pr_sanitizer  }}'>{{ $rooms->room  }}</option>
         @endforeach
    </select>
</div>

<strong data-price="0">$</strong>

I want to beable to combine the other drop-downs not the same ones. If I choose 1 room in the drop-down and then 5 in that same drop-down I don't want it to count 6. I do need it to count the rooms and then the other drop-downs

Upvotes: 0

Views: 462

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

One easy fix is to iterate through all the selects on the change, else you need to maintain the previously selected value for each select then subtract it from currPrice then add current value

var $selects = $("select").change(function () {
    var total = 0;
    $selects.each(function () {
        var price = parseFloat($(this).find("option:selected").data("price")) || 0;
        total += price;
    })
    $("strong").text('$ ' + total);
})

Demo: Fiddle

Upvotes: 1

Related Questions