jQuery addClass example

Change class name on click in jQuery

by uskaman2000

HTML

<form class="variants" action="/cart">
  <div class="price prc-new"><span>23,00</span> Р/</div>
  <select id="select-product" name="variant">
    <option value="56" data-price="23,00" data-compare-price="0,00 руб">грамм</option>
    <option value="61" data-price="230,00" data-compare-price="0,00 руб">килограмм</option>
  </select>
  <div class="product_count_label">×</div>
  <div class="product_count_input">
    <input class="amount" type="text" name="amount" value="1">
    <span class="plus" data-change="+1"></span>
    <span class="minus" data-change="-1"></span>
  </div>
  <div class="total_price">23,00</div>
</form>

CSS

.plus {
  width: 0;
  height: 0;
  border-width: 0 7px 9px 7px;
  border-color: transparent transparent #C2C2C2 transparent;
  border-style: solid;
  display: inline-block;
  top: 0px;
  right: 11px;
  position: absolute;
}

.minus {
  width: 0;
  height: 0;
  border-width: 9px 7px 0 7px;
  border-color: #C2C2C2 transparent transparent transparent;
  border-style: solid;
  display: inline-block;
  position: absolute;
  bottom: 2px;
  right: 11px;
}

.plus:hover,
.minus:hover {
  cursor: pointer;
}

.product .price,
.products .price {
  color: #6D2A25;
  font-size: 20px;
  font-weight: bold;
  line-height: 35px;
  margin: auto 0;
}

.product_count_input {
  position: relative;
  width: 200px;
}

JavaScript

function calcSum() {
  const
    price = $('[name="variant"] option:checked').data('price').replace(',', '.'),
    amount = $('[name="amount"]').val();
  $('.total_price').text((price * amount).toFixed(2).replace('.', ','));
}
$('[name="variant"]').on('change', function() {
  $('.price.prc-new span').text($(this).find('option:checked').data('price'));
  calcSum();
});

$('[name="variant"]').on('change', calcSum);
$('[data-change]').click(function() {
  const
    change = +$(this).data('change'),
    $amount = $('[name="amount"]');
  $amount.val(Math.max(1, +$amount.val() + change));
  calcSum();
});