如果单击具有指定功能的按钮,如何在输出框的下拉列表中显示选项的值? 我是编程新手,并不太懂。
/* This function is meant to take the value of the selected option and
display it in the output textbox */
function scoringValue() {
var chosenOne = document.getElementById("totalPoints").value + document.getElementById("options").value;
document.getElementById("totalPoints").value = chosenOne;
}
我对在此处分配值感到困惑
<p>
Scoring:
<select id="options">
<option value="3">1</option>
<option value="2">2</option>
<option value="7">3</option>
<option value="6">4</option>
<option value="8">5</option>
</select>
<input type="button" id="findScore" value="Score" onclick="return scoringValue()" />
Total Points: <input type="text" id="totalPoints" value=0 disabled="disabled" class="output" />
答案 0 :(得分:1)
您的代码中需要parseInt
个值,因为它们以字符串形式存在。因此,如果您将两个字符串“2”+“2”相加,则结果将为“22”。所以答案是:使用parseInt
将字符串转换为数字以正确加总它们。这是一个例子:
function scoringValue() {
var chosenOne = parseInt(document.getElementById("totalPoints").value, 10) +
parseInt(document.getElementById("options").value, 10);
document.getElementById("totalPoints").value = chosenOne;
}
<p>Scoring:<select id="options">
<option value="3">3</option>
<option value="2">2</option>
<option value="7">7</option>
<option value="6">6</option>
<option value="8">8</option>
</select>
<input type="button" id="findScore" value="Score" onclick="scoringValue()" />
Total Points: <input type="text" id="totalPoints" value=0
disabled="disabled" class="output" />
答案 1 :(得分:0)
您可以使用parseInt将值从string转换为int,然后执行计算。
示例:
function scoringValue() {
var totalPoints = parseInt(document.getElementById("totalPoints").value, 10);
var optionsValue = parseInt(document.getElementById("options").value, 10);
var chosenOne = totalPoints + optionsValue;
document.getElementById("totalPoints").value = chosenOne;
}