【发布时间】:2011-11-13 11:45:00
【问题描述】:
当然,这不应该这么难吗?
我有一个<select>,当然也有<options>。这些options总是采用数字格式,因为它们是由用户动态添加到列表中的。
然后我需要从列表中获取所有这些选项,将它们放入一个数组,然后对数组执行逻辑。我试过四处搜索,但一切都与 jquery 或 php 相关——而且我使用的是普通的旧 HTML 和 JavaScript。
select 是滚动框格式:
<select id="selectBox" name="select" size="15" style="width:190px;">
<!-- <options> are added via javascript -->
</select>
目前,我正在使用此 JavaScript 来获取元素,但它不起作用:
//Calculate all numbers
var x=[];
function calculate()
{
for (var i = 0; i < 999; i++)
{
x[i]=selectbox.options[i].value;
alert(x[i]);
}
}
Calculate() 由按钮调用。事情发生了严重的错误,我无法解决。 selectbox 以前被定义为 var selectbox = document.getElementById("selectBox");,我知道这是可行的。
警报只是被调用,所以我可以尝试调试这个东西......
我使用999 的数字是因为我不知道如何计算<select> 中有多少元素(因为它是滚动框格式)。
解决方案必须为 javascript,并且列表框必须采用该滚动框格式。
提前感谢您的帮助!
编辑 -- 好的,更多代码可以帮助解决这个问题。
<form id="aggregateForm">
<input id="inputNum" value="" type="text"><input id="addnum" value="Add" onclick="add();" type="button">
<br>
<select id="selectBox" name="select" size="15" style="width:190px;">
</select>
<br>
<input id="calculate" value="Calculate" onclick="calculate();" type="button"><input id="reset" value="Reset" onclick="reset();" type="button">
</form>
<script type="text/javascript">
var selectbox = document.getElementById("selectBox");
function add()
{
//Function to add a new number to the list of digits
//Parses an integer to ensure everything works okay
if(IsNumeric(document.getElementById("inputNum").value) == true)
{
selectbox.options[selectbox.options.length] = new Option(document.getElementById("inputNum").value, document.getElementById("inputNum").value);
inputNum.focus();
}
else if(IsNumeric(document.getElementById("inputNum").value) == false)
{
alert("I'm sorry, but you have entered an invalid number. Please enter a number into the input box.");
inputNum.focus();
}
}
//Calculate all numbers
var x=[];
function calculate()
{
for (var i = 0; i <selectbox.options.length; i++)
{
x[i]=selectbox.options[i].value;
alert(x[i]);
}
}
//IsNumeric function coding taken from http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric, code by Joel Coehoorn
function IsNumeric(input)
{
return (input - 0) == input && input.length > 0;
}
</script>
【问题讨论】:
-
你为什么不想使用jQuery?分配给警报是一个错字,对吗?
alert=(x[i]); -
我有可以使用 javascript(说来话长),抱歉。为什么
alert错了? -
jQuery 是 Javascript。
alert(x[i])看起来更像你想要的。或者可能是循环之后的console.log(x)。 -
Ohhh,现在修复警报..也许它正在工作...?而且我必须自己用纯 Javascript 编写所有的程序。
-
不,警报仍然不起作用 - 一定是我的编码。
标签: javascript arrays select