2017-07-16 59 views
0
<!DOCTYPE html> 
<html> 
<body> 

<h2>List Totals</h2> 

<p>Display myList Total:</p> 

<p id="total"></p> 

<form action="/action_page.php"> 
    <select id = "myList"> 
    <option>0</option> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
     </select> 
<p></p>  
<form action="/action_page.php"> 
    <select id = "myList2"> 
    <option>0</option> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
     </select> 

</form> 

<script> 
var x = document.getElementById("myList"+"myList2"); 
document.getElementById("total").innerHTML = x; 
</script> 

</body> 
</html> 

對不起,這是我第一次嘗試使用兩個下拉菜單製作HTML/JS表單,並添加了總數值。它似乎不讓我有一個總數。我究竟做錯了什麼?謝謝大家!爲什麼我的代碼不顯示總數?

所有的
+0

看起來您正試圖獲取元素「myListmyList2」而不是獲取這兩個元素並添加它們。看看你的括號在腳本的第一行。 – Kdawg

+0

此外,爲了獲取所選選項的值,請參閱https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript – Kdawg

回答

0
<form action="/action_page.php"> 
    <select id = "myList" onchange="recalc()"> 
    <option>0</option> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
     </select> 
<p></p> 
<form action="/action_page.php"> 
    <select id = "myList2" onchange="recalc()"> 
    <option>0</option> 
    <option>1</option> 
    <option>2</option> 
    <option>3</option> 
     </select> 

</form> 

<script> 
function recalc() { 
var x = parseInt(document.getElementById("myList").value) 
     + parseInt(document.getElementById("myList2").value); 
    console.log(x , ' x '); 
    document.getElementById("total").innerHTML = x; 
} 
+0

非常感謝您的幫助! –

0
  • 首先,你有沒有附加任何時候對你的元素。

  • getElementById元素的期望ID因此您的語法無效。

  • 使用ternary-operatorNumber將字符串轉換爲數字作爲value屬性返回字符串,因此它將被連接而不添加。

var select1 = document.getElementById("myList"); 
 
var select2 = document.getElementById("myList2"); 
 

 
select1.onchange = manipulate; 
 
select2.onchange = manipulate; 
 

 
function manipulate() { 
 
    document.getElementById("total").innerHTML = +select1.value + +select2.value; 
 
}
<h2>List Totals</h2> 
 
<p>Display myList Total:</p> 
 
<p id="total"></p> 
 
<form action="/action_page.php"> 
 
    <select id="myList"> 
 
    <option>0</option> 
 
    <option>1</option> 
 
    <option>2</option> 
 
    <option>3</option> 
 
     </select> 
 
    <p></p> 
 
</form> 
 
<form action="/action_page.php"> 
 
    <select id="myList2"> 
 
    <option>0</option> 
 
    <option>1</option> 
 
    <option>2</option> 
 
    <option>3</option> 
 
     </select> 
 
</form>

+0

非常感謝您的幫助! –

0

更改此:

var x = document.getElementById("myList"+"myList2"); 
document.getElementById("total").innerHTML = x; 

這樣:

var x1 = document.getElementById("myList"); 
var x2 = document.getElementById("myList2"); 
var value1 = x1.options[x1.selectedIndex].text; 
var value2 = x2.options[x2.selectedIndex].text; 
document.getElementById("total").innerHTML = value1 + value2; 

,並添加HTML標記使用id = 「總」。例如,如下所示:

<span id="total"></span> 
+0

非常感謝您的幫助! –

相關問題