2014-07-14 43 views
0

所以我試圖根據選擇值更改變量並在更改時顯示它。我已經通過以靜態方式設置變量來實現它的工作,但如果選擇值被更改或增加,我不知道如何更改變量。Javascript onchange - 根據選擇值更改變量

在這種情況下,我試圖根據數量更改價格。如果數量大於X,則價格變爲Y.請記住我是JavaScript新手,因此請保持您的答案基本。

這是我當前的代碼:

HTML

<label>Single User</label> 
<select class="input-mini" name="singleuser" id="singleuser" onchange="changed(this, 0, 34.95)"> 
    <option value="0">0</option> 
    <option value="1">1</option> 
</select>&nbsp;&nbsp;<font size="4"><b>@ $34.95/mo</b></font> 

的Javascript

var size = 36; 
var cart = new Array(); 

for (var j = 0; j < size; j++) //initialize cart to all 0 
    cart[j] = 0; 

function changed(me, id, price) { 
    var amount = me.options[me.selectedIndex].value; //quantity passed 
    var t_price = amount * price; //multiply operation 
    cart[id] = t_price; //update cart array 
    update_spans(); 

    document.getElementById(id).value = amount; //update quantity for final page 
} 
function update_spans() { 
    put("cart0", cart[0]); 
} 
function put(name, price) { 
    try { 
     price = (Math.round(price * 100)/100); //round 
     price = price.toFixed(2); //two decimal places 
     document.getElementById(name).innerHTML = price; //put into span 
    } catch (err) { 
     //error 
    } 
} 
+1

查看我的回答,讓我知道如果你發現它有用:) – hex494D49

+0

這不完全是我想要做的。再讀一遍,我看到我解釋得不好。我試圖用更高的數量來改變單位價格。如果數量高於X,則單價應該變爲更低的價格。數量折扣! – Arringar

+0

檢查更新的答案。正如你所看到的,我添加了一個折扣數組。數組的索引保存該數量的折扣值,因此折扣[0] = 0%折扣,這意味着對於數量0,沒有折扣;此外,折扣[1] = 5%,這意味着對於數量1,折扣爲5%等等。當然,您可以更改這些值,並假設爲數量2及以上定義折扣。在這種情況下,折扣數組看起來像這樣[0,0,5,10,15,20,25] ...是否清楚:) – hex494D49

回答

1

改變你的HTML和JavaScript部分下面

// HTML 
<label>Single User</label> 
<select class="input-mini" name="singleuser" id="singleuser" onchange="changed(this, 0, 34.95)"> 
    <option value="0">0</option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option>  
</select> 
&nbsp;&nbsp; 
<span id="price">@ $34.95/mo</span> 

// JavaScript (this is all you need) 
var size = 36, cart = []; 
var discount = [0, 5, 10, 15, 20, 25, 50]; 

for(var j = 0; j < size; j++) cart[j] = 0; 

function changed(me, id, price){ 
    var amount = me.options[me.selectedIndex].value; 
    var p_discount = amount * price * (discount[me.selectedIndex]/100); 
    var t_price = (amount * price) - p_discount; 
    cart[id] = t_price; 

    r_price = (Math.round(t_price*100)/100); 
    r_price = r_price.toFixed(2); 

    document.getElementById('price').innerHTML = '@ ' + r_price + '/mo'; 
} 

代碼檢查WOR國王jsBin

+0

這就是我所需要的。謝謝@ hex494D49 !!! – Arringar