2017-10-08 62 views
0

我有各種輸入,每一個通過數據屬性不同的價格:如何總結從輸入各種數據ATTR和價值

<%= f.number_field :item, class: "test", :data => {:price => '10.25'} 

用戶可以選擇他們想要的項目數,所以我需要乘項目價格選擇的項目數量。

$(document).ready(function() { 
    $(".test").on('change', function() { 
    a = $(".test").val() * $(".test").data("price") + "€"; 
    $(".resultado").html(a); 
    }); 
}); 

這1個輸入的偉大工程,但因爲我有4個輸入,每個都有不同的價格,我需要得到的總價格爲他們的9。

<%= f.number_field :item, class: "test", :data => {:price => '10.25'} %> 
<%= f.number_field :seconditem, class: "test", :data => {:price => '10'} %> 
<%= f.number_field :thirditem, class: "test", :data => {:price => '10.75'} %> 
<%= f.number_field :fourthitem, class: "test", :data => {:price => '10.50'} %> 

基本上,我需要這樣的:

A: Number of items * price of each item 
Sum all of the "A" values 

如何修改才能達到這個我的腳本/類?

非常感謝。

回答

1

假設每個項目都有不同的價格和數量,下面的重構應該工作。 Here's a JSFiddle with the working demo

$(document).ready(function() { 
    $(".test").on('change', function() { 
    var total = 0; 
    $.each($('.test'), function(key, value) { 
     total += $(this).val() * $(this).data("price"); 
    }); 
    $(". resultado").html(total + "€"); 
    }); 
}); 
+0

這完成了絕招!非常感謝! – Gibson

2

您可以使用.each()乘返回值.data()

$("input[type=button]").on("click", function() { 
 

 
    let n = 1; 
 

 
    $(".test").each(function() { 
 
    n *= $(this).data().price; 
 
    }); 
 

 
    $(".resultado").html(n); 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
 
</script> 
 
<input type="button" value="click" /> 
 
<div class="test" data-price="1"></div> 
 
<div class="test" data-price="2"></div> 
 
<div class="test" data-price="3"></div> 
 
<div class="test" data-price="4"></div> 
 

 
<div class="resultado"></div>