如何在不使用元素的 id 的情况下使用 javascript 访问表单元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17259329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access form element with javascript without using element's id
提问by Shatadru Bandyopadhyay
I want to access form elements by using javascript. The form is generated dynamically so the name, id of the form and the elements are variable. I want to get the id value of a textarea
inside it by providing the name of the form, which is generated by a different script.
我想使用 javascript 访问表单元素。表单是动态生成的,因此表单的名称、ID 和元素都是可变的。我想textarea
通过提供由不同脚本生成的表单名称来获取其中的 a 的 id 值。
For instance:
例如:
<form method=post name=form33>
<textarea id=466 cols=50 rows=5></textarea>
<input name=submit33 onclick=postCmnt(33) value=Post type=button>
</form>
and I have the name of the form name "form33" and I need its textarea
id that is 466 as output...
我有表单名称“form33”的名称,我需要它的textarea
id 为 466 作为输出...
Javascript Generating The Form:
Javascript 生成表单:
function openComment(id, msgid, div) {
var div = document.getElementById(div);
div.innerHTML = "<form method=post name=form"+id+">
<textarea id="+msgid+" cols=50 rows=5></textarea>
<input name=submit"+id+" onclick=postCmnt("+id+") value=Post type=button>
</form>"
}
Javascript that need to access the form
需要访问表单的Javascript
Here is my attempt to access the id
name of textarea
by providing form name.
这是我通过提供表单名称来访问id
名称的尝试textarea
。
function postCmnt(id){
var msgid=document.forms["form"+id].elements[0].id.value;//the text area's id
var msg=document.getElementById(msgid).value;//value of text area
//rest scripts goes here
}
Information:
信息:
- Form is not static generated by call to the function openComment()
- predicting number of form in a page is not possible as it depends upon user input .Though the textarea is the 1st element of the form .
- 表单不是通过调用函数 openComment() 生成的静态
- 预测页面中表单的数量是不可能的,因为它取决于用户输入。尽管 textarea 是表单的第一个元素。
采纳答案by Eyal Alsheich
You can add a hidden field that contains the msgid:
您可以添加一个包含 msgid 的隐藏字段:
Javascript Generating The Form:
Javascript 生成表单:
function openComment(id,msgid,div){
var div = document.getElementById(div);
div.innerHTML="<form method=post name=form"+id+">
<input type='hidden' id='theid"+id+"' value='"+msgid+"'>
<textarea id="+msgid+" cols=50 rows=5></textarea>
<input name=submit"+id+" onclick=postCmnt("+id+") value=Post type=button>
</form>"
}
and then just get the value directly:
然后直接获取值:
function postCmnt(id){
var msgid=document.getElementById("theid"+id).value;//the text area's id
var msg=document.getElementById(msgid).value;//value of text area
//rest scripts goes here
}
回答by paulusm
If there is only one form in the documents, you can do
如果文件中只有一种形式,您可以这样做
document.forms[0]