2016-03-02 437 views
2

我有3個輸入字段來計算價格和折扣百分比。第一場爲正常價格。我想要做的是: 如果用戶更改百分比值,將計算折扣價格(2位小數),如果用戶更改折扣價格,則會計算百分比。按價值或價值百分比計算百分比

目前我只成功了計算百分比:

function calculatePrice() { 
    var percentage = $('input[name=\'percentage\']').val(), 
     price = $('input[name=\'price\']').val(), 
     calcPrice = price - ((price/100) * percentage), 
     discountPrice = calcPrice.toFixed(2); 
    $('input[name=\'discount\']').val(discountPrice); 
} 
function calculatePerc() { 
    var discountPrice = $('input[name=\'discount]\']').val(), 
     price = $('input[name=\'price\']').val(), 
     calcPerc = (price/100) * (price-discountPrice), 
     discountPerc = calcPerc.toFixed(); 
    $('input[name=\'percentage\']').val(discountPerc); 
} 

我的HTML:

<input type="text" name="price" value="1000"> 
<input type="text" name="percentage" onkeyup="calculatePrice()"> 
<input type="text" name="discount" onkeyup="calculatePerc()"> 

這裏是我的小提琴:https://jsfiddle.net/90bo9okg/

+1

刪除轉義字符。你不需要他們。 https://jsfiddle.net/DinoMyte/90bo9okg/1/ – DinoMyte

+0

@DinoMyte這個小提琴可以工作,但我認爲其目的是將discountPerc除以100(即後50.50而不是5050) – SvenAelterman

+2

是。沒有看過之前的計算。這是更新的:https://jsfiddle.net/DinoMyte/90bo9okg/2/ – DinoMyte

回答

2

var $price  = $("input[name='price']"), 
 
    $percentage = $("input[name='percentage']").on("input", calculatePrice), 
 
    $discount = $("input[name='discount']").on("input", calculatePerc); 
 
    
 

 
function calculatePrice() { 
 
    var percentage = $(this).val(); 
 
    var price  = $price.val(); 
 
    var calcPrice = (price - (price * percentage/100)).toFixed(2); 
 
    $discount.val(calcPrice); 
 
} 
 

 
function calculatePerc() { 
 
    var discount = $(this).val(); 
 
    var price = $price.val(); 
 
    var calcPerc = 100 - (discount * 100/price); 
 
    $percentage.val(calcPerc); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
Regular Price : <input type="text" name="price" value="1000"><br> 
 
Discount Percentage : <input type="text" name="percentage"><br> 
 
Discounted Price : <input type="text" name="discount">

+0

謝謝!我只是把這條線100(折扣* 100 /價格)改爲(100-(折扣* 100 /價格))toFixed(),因爲當價格是103而折扣價格是18時,它計算出一個奇怪的百分比:) – Dejavu