Javascript For Loop On Array of Input fields 与 document.getElementById 相关
我有一个服务器端脚本为我创建大量文本字段。当我希望用户填写它们并提交数据时。我知道有多少个字段,因为服务器也会发送一个计数。
然后我尝试将它们连接成一根长绳,中间有一个垫片。但我在获取数组的值时遇到问题。
用代码更好地解释。
这行得通,
<script>
function Submit() {
var spacer = ":";
var mycount = document.getElementById('counter').value;
var usertext = '';
var x=0;
for(x = 0; x **<= 2**; x++){
usertext = usertext + document.getElementById('description[' + x + ']').value + spacer ;
}
</script>
这行不通。
<script>
function Submit() {
var spacer = ":";
var mycount = document.getElementById('counter').value;
var usertext = '';
var x=0;
for(x = 0; x **<= mycount**; x++){
usertext = usertext + document.getElementById('description[' + x + ']').value + spacer ;
}
</script>
这是我的身体
<textarea id='counter' name='counter'>2</textarea>
<textarea id='description[0]' name=''description'>zero</textarea>
<textarea id='description[1]' name=''description'>one</textarea>
<textarea id='description[2]' name=''description'>two</textarea>
<button type="button" onclick="Submit()" >Save</button>
这是 Firebug 给我的错误:
document.getElementById("描述[" + x + "]") 为空
有谁知道如何做到这一点?
谢谢
I have an serverside script making an amount of text fields for me. When I want a user to fill them up, and submit data. I know how many fields there are, as the server also sends a count.
I am then trying to join them into a long string with a spacer between. But I am having trouble getting the value of the array.
Better explained with code.
This works
<script>
function Submit() {
var spacer = ":";
var mycount = document.getElementById('counter').value;
var usertext = '';
var x=0;
for(x = 0; x **<= 2**; x++){
usertext = usertext + document.getElementById('description[' + x + ']').value + spacer ;
}
</script>
This does not work.
<script>
function Submit() {
var spacer = ":";
var mycount = document.getElementById('counter').value;
var usertext = '';
var x=0;
for(x = 0; x **<= mycount**; x++){
usertext = usertext + document.getElementById('description[' + x + ']').value + spacer ;
}
</script>
This is my body
<textarea id='counter' name='counter'>2</textarea>
<textarea id='description[0]' name=''description'>zero</textarea>
<textarea id='description[1]' name=''description'>one</textarea>
<textarea id='description[2]' name=''description'>two</textarea>
<button type="button" onclick="Submit()" >Save</button>
This is the error Firebug gives me:
document.getElementById("description["
+ x + "]") is null
Does anyone know a way to do this?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尽管您的 HTML 无效(例如不平衡的引号),但它对我来说工作正常。更好的问题是这样做的目的是什么。为什么不直接提交表格呢?
It works fine for me despite your invalid HTML (e.g. unbalanced quotes). The better question is what the purpose of this is. Why not just submit the form as is?
在将
mycount
应用于 for 循环之前,使用parseInt
获取mycount
的整数值:Before applying
mycount
to a for loop take the integer value ofmycount
withparseInt
: