<!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 :(得分: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;
}
答案 1 :(得分:0)
首先,您没有将任何事件附加到您的元素。
getElementById
期望的元素ID,因此您的语法无效。
使用ternary-operator
或Number
将字符串转换为数字,因为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;
}
&#13;
<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>
&#13;
答案 2 :(得分: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;
并在id =“total”的HTML标记中添加。例如,所以:
<span id="total"></span>