JavaScript рассчитывает только выбранный флажок - PullRequest
0 голосов
/ 21 октября 2019

У меня есть список продуктов, и я хочу рассчитать их цены, когда их флажок установлен, в настоящее время мой код будет рассчитывать все флажки, включая непроверенные.

JavaScript

<script>
    $(document).ready(function () {
        $(".bundlechecked").on('click', function () { //div checkbox
            var pp = 0;
            $(".thisPrice").each(function() { //input where price comes from
                if(!isNaN(this.value) && this.value.length!=0) 
                {
                    pp += parseFloat(this.value);            
                }         
            });
            console.log(pp);
        });
    });
</script>

Blade (View)

@foreach($bundles as $product)
    <div class="bundlechecked checkbox"> // how we define which item is selected (bundlechecked)
        <label><input type="checkbox" value="{{$product->id}}">
            <div class="product-thumb">
                <div class="image"><img src="{{url('/')}}/images/{{$product->imageOne}}" alt="{{$product->imageOne_alt}}" title="{{$product->title}}" class="img-responsive" /></div>
                <div class="caption">
                <h4>{{$product->title}}</h4>
                @if(!empty($product->newprice))
                <p class="price">
                    <span class="price-new">{{ __('frontend.rp') }} {{ number_format($product->newprice, 0) }}</span>
                    <input type="hidden" class="thisPrice" value="{{$product->newprice}}"> // getting price of selected item
                    <span class="price-old">{{ __('frontend.rp') }} {{ number_format($product->price, 0) }}</span>
                    <span class="saving">
                    - {{number_format(($product->price - $product->newprice) / $product->price * 100, 0) }}%
                    </span>
                </p>
                @else
                <p class="price"> {{ __('frontend.rp') }} {{ number_format($product->price, 0) }} </p>
                <input type="hidden" class="thisPrice" value="{{$product->price}}"> // getting price of selected item
                @endif
                </div>
            </div>
        </label>
    </div>
@endforeach

Я прокомментировал код для лучшего понимания

Есть идеи?

Ответы [ 3 ]

1 голос
/ 21 октября 2019

Попробуйте это

  • onchange событие лучше для этой цели
  • Ключ должен получить только те ценовые узлы, которые проверены

var price = 0;
const calculatePrice = function(e) {
  let val = $(e).siblings().first().find('.caption .thisPrice').first().val();
  if(!isNaN(val) && val.length != 0){
      price += parseInt(val);
  }  
};

$(document).ready(function(){
  $('.bundlechecked').on('change', function(e){
    price = 0;
    $('.bundlechecked:checked').each((i, e, s) => calculatePrice(e));
    console.clear();
    console.log('Total price =>', price);
  });  
});
label { display: block;}
label * { display: inline;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
  <input type="checkbox" class="bundlechecked">
  <div class="product-thumb">                
      <div class="caption">
        <h4>Product One - 10</h4>
        <input type="hidden" class="thisPrice" value="10">
      </div>
  </div>
</label>
<label>
  <input type="checkbox" class="bundlechecked">
  <div class="product-thumb">                
      <div class="caption">
        <h4>Product Two - 25</h4>
        <input type="hidden" class="thisPrice" value="25">
      </div>
  </div>
</label>
<label>
  <input type="checkbox" class="bundlechecked">
  <div class="product-thumb">                
      <div class="caption">
        <h4>Product Three - 12</h4>
        <input type="hidden" class="thisPrice" value="12">
      </div>
  </div>
</label>
<label>
  <input type="checkbox" class="bundlechecked">
  <div class="product-thumb">                
      <div class="caption">
        <h4>Product Four - 30</h4>
        <input type="hidden" class="thisPrice" value="30">
      </div>
  </div>
</label>
<label>
  <input type="checkbox" class="bundlechecked">
  <div class="product-thumb">                
      <div class="caption">
        <h4>Product Five - 15</h4>
        <input type="hidden" class="thisPrice" value="15">
      </div>
  </div>
</label>
1 голос
/ 21 октября 2019

Попробуйте это:

    <script>
        $(document).ready(function () {
            $(".bundlechecked").on('click', function () { //div checkbox
                var pp = 0;
                $(".thisPrice").each(function() { //input where price comes from
                     var checkbox = $(this).parent("label").find("input[type=checkbox]");
                     if (checkbox.prop('checked') && !isNaN(this.value) && this.value.length!=0)
                     {
                         pp = +pp + +parseFloat($(this).val());
                     }
                });
                console.log(pp);
            });
        });
    </script>

Вот JSFiddle: https://jsfiddle.net/leonenco/8ojdesz6/26/

0 голосов
/ 21 октября 2019

Попробуйте это

$(document).ready(function () {
        $("input[type='checkbox']").on('click', function () { 
            if($(this).is(':checked')) {
            var getCurrentParent = $(this).parents('.bundlechecked').first();
            var pp = [];
            $(getCurrentParent).find(".thisPrice").each(function() { //input where price comes from
                if(!isNaN(this.value) && this.value.length!=0) 
                {
                    pp.push(this.value);            
                }         
            });
            console.log(pp);
            }
        });
    });
...