calcPrice

native calc

by Vitaliy T

JavaScript

/*live calculate block*/
// round item function
(function() {
  function decimalAdjust(type, value, exp) {
    if (typeof exp === 'undefined' || +exp === 0) {
      return Math[type](value);
    }
    value = +value;
    exp = +exp;
    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
      return NaN;
    }
    value = value.toString().split('e');
    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
    value = value.toString().split('e');
    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
  }
  if (!Math.round10) {
    Math.round10 = function(value, exp) {
      return decimalAdjust('round', value, exp);
    };
  }
})();
// get total function 
function getNativeTotalFunc(){
    var getNativeTotal = document.querySelectorAll('span.price-sum');
    var superTotal = 0;
    for(var i = getNativeTotal.length - 1; i >= 0; i--){
        var sp_item = getNativeTotal[i].innerText;
        superTotal = superTotal + Number(sp_item);  
    };
    document.getElementById('js_subtotal_calc').innerHTML = superTotal;
};
// get total on page load
getNativeTotalFunc();
// get item Amount
var inputsQ = document.querySelectorAll('.ms2_form input[type="number"]');
for(var i = inputsQ.length - 1; i >= 0; i--){
    inputsQ[i].onchange = function(){
        var itemCount = this.value;
        var getParents = this.parentElement.parentElement.parentElement.getAttribute('id');
        var getPrice = document.getElementById(getParents).getElementsByClassName('price-row')[1].innerText;
        document.getElementById(getParents).getElementsByClassName('price-sum')[1].innerText = Math.round10(itemCount * getPrice, -2);
        getNativeTotalFunc();
    };
};