2015-09-05 26 views
0

我試圖乘以從下拉列表中選擇的1個項目(項目的價格必須保存在一個數組中)的用戶輸入的「數量」。另外,當用戶選擇不同的項目時,右側的圖片會發生變化。由於我是JavaScript/HTML中的初學者,因此在製作數量項目函數時遇到問題。請不要使用jQuery代碼,純粹是JavaScript/HTML。以下是一段代碼。任何人都可以幫我修好嗎?謝謝。使用JavaScript的HTML內計算

的JavaScript:

function swapImage(dropdown){ 
    var value= dropdown.options[dropdown.selectedIndex].value; 
    var edit_save = document.getElementById("imageToSwap"); 
    edit_save.src = value; 
    alert(value); 
} 

var priceList = new Array(4); 
pricelist[0]=10; 
pricelist[1]=12; 
pricelist[2]=14; 
pricelist[3]=11;  

function calculateTotal(dropdown){ 
    var total=priceList[dropdown.selectedIndex]*number; 
} 

HTML:

<img id="imageToSwap" src="gnar.png" alt="CSS Style Tag"> 

<br><br> 

<select id="dlist" onchange="swapImage(this)"> 
    <option value=gnar.png>Gnar Hoodie €10</option> 
    <option value=blitz.png>Blitz T-Shirt €12</option> 
    <option value=corki.png>Corki Hoodie €14</option> 
    <option value=graves.png>Graves T-Shirt €11</option> 
</select> 

<br><br> 

<label name="Quantity">Quantity of the item</label> 
<input type="number" name="Quantity" min="1" required=""><br> 

<p class="totals" id="totalprice">Total Price:</p> 
+0

你'calculateTotal()'函數不返回任何東西,也不會更新以任何方式DOM ,你在期待什麼?另外,你在哪裏打電話? – azium

+0

您需要設置相同的名稱:'priceList'無處不在:您有'pricelist [...] = ...'用小寫字母l ... – Zimmi

+0

您還缺少一個半角標記,冒號在您定義'priceList'的行。 –

回答

0

我做了一個http://jsfiddle.net/p5rmpjet/7/。我改變了一下,所以價格被存儲在你的html中,而不是每次有新項目時將它們添加到你的JS中。

function swapImage(e){ 
    var image = document.getElementById("imageToSwap"); 
    console.log(image); //image tag 
    image.src = e.value; 
} 

function updatePrice(quantity){ 
    var edit_save = document.getElementById("dlist"); 
    console.log(edit_save.options[ edit_save.selectedIndex].id); //price of item 

    var quantity = document.getElementById("quantity").value; 
    console.log(quantity); 

    var price = edit_save.options[edit_save.selectedIndex].id; 

    var total = quantity * price; 
    console.log(total); 
    document.getElementById("totalprice").innerHTML = total; 
} 

function updateItem(price){ 
    var price = edit_save.options[edit_save.selectedIndex].id; 
} 

注意:更新小提琴與onchange事件的第二功能選擇項目http://jsfiddle.net/p5rmpjet/7/

+0

Omg謝謝它工作正常,但有沒有辦法立即更新總價?因爲如果您在選擇一件商品後更改數量,價格不會變化 –

+0

Nvm修復了這個問題,非常感謝很多人的幫助<3 –

+0

@CarlCarl我更新了它以涵蓋物品選擇和數量,但是如果您那很棒。不客氣,很高興它解決了。不要忘記接受答案。 – amespower