简体   繁体   English

根据输入数量(数量)变化计算价格

[英]Calculate price based on input number (quantity) change

I have multiple selects that populate form with products and prices. 我有多个选择,其中包含产品和价格的表格。 Then I am calculating full price of all products and that works fine but there is number input field in form for quantity and I cant calculate price based on products quantity. 然后,我正在计算所有产品的全价,并且效果很好,但是在数量表中有数字输入字段,因此我无法根据产品数量来计算价格。

Here is fiddle: http://jsfiddle.net/fpm971fb/ 这是小提琴: http : //jsfiddle.net/fpm971fb/

I tried with this code: 我尝试使用以下代码:

jQuery('input.selected-product-quantity').bind('focus blur select change click dblclick mousedown mouseup mouseover mousemove mouseout keypress keydown keyup', function(){
       pr=jQuery('.priceClass').text();
       nr=jQuery('.selected-product-quantity').val();
       calc=pr*nr;
       console.log(pr+"*"+nr);
       jQuery('.priceClass').html(calc);
});

But when this code is entered inside on change function (see in fiddle) it shows huge numbers like it adds one to another. 但是,当在更改函数中输入此代码时(参见小提琴),它显示出巨大的数字,就像将一个数字相加一样。 And when its outside that function then nothing happens. 而当它超出该功能时,则什么也不会发生。
How can I properly calculate full price with quantity? 如何正确计算带数量的全价?

Try This : 尝试这个 :

$('input.selected-product-quantity').change(function(){
  var quantity = $(this).val();
  var price = $('.priceClass').text();
  var calprice = parseInt(price) * parseInt(quantity);
  $('.priceClass').text(calprice);
});

Try converting your input values to number before any calculation : 在进行任何计算之前,请尝试将输入值转换为数字:

$('input.selected-product-quantity').on('change', function(){
    var pr = Number($('.priceClass').text());
    var nr = Number($('.selected-product-quantity').val());
    var calc = pr * nr;
    console.log(pr+"*"+nr);
    $('.priceClass').html(calc);
});

Try putting the following code inside a function named TotalPrice() , 尝试将以下代码放入名为TotalPrice()的函数中,

function TotalPrice(){
    var sum = 0;
    jQuery('.priceClass').each(function () {
    sum += Number(jQuery(this).text() * parseInt($(this).next().next().children("input").val()));
        console.log(sum);
    });
    jQuery(".fullPrice").html("<b>Full price: </b>" + sum); 
}

and Then call it from inside the select element change (Where this function was previously coded). 然后从选择元素更改内部调用它(此函数以前已编码)。

Now as the elements are dynamically loaded you are facing a problem to bind events with them. 现在,随着元素的动态加载,您面临着将事件与它们绑定的问题。 So I suggest to be little tricky about it. 因此,我建议对此不要太棘手。 Try this way, 试试这个

$("body").on("keyup", function(){
    TotalPrice();
});

When the body changes (which is a already loaded element in DOM) you call the TotalPrice() function and calculate total price. 当正文更改时(这是DOM中已经加载的元素),您可以调用TotalPrice()函数并计算总价。 It's not the best solution I guess. 我猜这不是最好的解决方案。 So I appreciate suggestion. 因此,我感谢您的建议。

jsFiddle jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM