我正在创建一个包含选择输入的表单,并且这些值会累加到某个分数。我无法从选择中添加值并将总和输入到总输入中以显示其测试的分数。
jscript:
function calculate_total(){
var elems = document.getElementsByClassName('Assessment');
var myLength = elems.length,
total = 0;
for (var i = 0; i < myLength; ++i) {
total += parseInt(elems[i].value * 1);
}
document.getElementById('ScoreTot').value = total;
}
HTML:
<cfselect name="SELECT1" id="select1" class="Assessment">
<option value="0"> OPTION 1 </option>
<option value="1"> OPTION 2 </option>
</cfselect>
<cfselect name="select2" id="select2" class="Assessment">
<option value="0"> OPTION 1 </option>
<option value="1"> OPTION 2 </option>
<option value="2"> OPTION 3 </option>
</cfselect>
<cfselect name="select3" id="select3" class="Assessment">
<option value="0"> OPTION 1 </option>
<option value="1"> OPTION 2 </option>
<option value="2"> OPTION 3 </option>
</cfselect>
Score: <cfinput type="text" name="ScoreTot" id="ScoreTot" value="">
答案 0 :(得分:1)
使用选择时,您需要使用所选选项的值,尤其是在您计划投放旧版浏览器时。
elems[i].options[elems[i].selectedIndex].value
而且,正如另一个答案所指出的那样,parseInt应该有一个基数。
function calculate_total(){
var elems = document.getElementsByClassName('Assessment');
var myLength = elems.length,
total = 0;
for (var i = 0; i < myLength; ++i) {
total += parseInt(elems[i].options[elems[i].selectedIndex].value * 1,10);
}
document.getElementById('ScoreTot').value = total;
}
答案 1 :(得分:1)
您的逻辑中存在一些错误。下面是一份工作副本,但首先是一些注意事项:
T
或<cfselect>
,所以此示例显示了有效的HTML。
<cfinput>
&#13;
function calculate_total() {
var els = document.getElementsByClassName('Assessment');
// always use var to declare variables in scope; they are global otherwise
var total1 = 0;
// Little benefit to storing the length elsewhere
// Use i++ instead of ++i
for (var i = 0; i < els.length; i++) {
// Use a radix to indicate base 10, I didn't see a need for the *1
total1 += parseInt(els[i].value, 10);
}
document.getElementById('ScoreTot').value = total1;
}
// Call your function somehow!
calculate_total();
&#13;
答案 2 :(得分:0)
此处不清楚何时需要执行该功能。 向dom添加一个按钮并将事件附加到它。
var e = document.getElementById('foo');
e.onclick = calculateTotal;
function calculateTotal(){
var elems = document.getElementsByClassName('Assessment');
var myLength = elems.length,
total = 0;
for (var i = 0; i < myLength; ++i) {
total += parseInt(elems[i].value * 1);
}
document.getElementById('ScoreTot').value = total;
}
<select name="SELECT1" id="select1" class="Assessment">
<option value="0"> OPTION 1 </option>
<option value="1"> OPTION 2 </option>
</select>
<select name="select2" id="select2" class="Assessment">
<option value="0"> OPTION 1 </option>
<option value="1"> OPTION 2 </option>
<option value="2"> OPTION 3 </option>
</select>
<select name="select3" id="select3" class="Assessment">
<option value="0"> OPTION 1 </option>
<option value="1"> OPTION 2 </option>
<option value="2"> OPTION 3 </option>
</select>
Score: <input type="text" name="ScoreTot" id="ScoreTot" value="">
<input type="button" id="foo" value="Add" />