如何使用JavaScript动态创建表单?

cha*_*987 18 javascript forms

我希望使用JavaScript动态地在HTML页面中的任何位置创建一个不可见的表单,然后自动提交.
我想创建下面给出的表单:

<form name='myForm' method='post' action='http://www.another_page.com/index.htm'>
<input type='text' name='myInput' value='Values of my input'>
<input type='hidden1' value='Hidden value 1'>
<input type='hidden2' value='Hidden value 2'>
</form>
Run Code Online (Sandbox Code Playgroud)

我尝试使用下面的JavaScript:

my_form=document.createElement('FORM');
my_form.name='myForm';
my_form.method='POST';
my_form.action='http://www.another_page.com/index.htm';
my_tb=document.createElement('INPUT');
my_tb.type='TEXT';
my_tb.name='myInput';
my_tb.value='Values of my Input';
my_tb.appendChild(my_form);
document.body.add(my_form,document.body.elements[0]);
document.my_form.submit();
Run Code Online (Sandbox Code Playgroud)

但不工作?我怎样才能做到这一点?请帮忙.

Sam*_*fel 25

您将表单元素添加为文本框的子项.

my_tb.appendChild(my_form);
Run Code Online (Sandbox Code Playgroud)

应该

my_form.appendChild(my_tb);
Run Code Online (Sandbox Code Playgroud)

此外,我没有看到您尝试创建隐藏元素的位置,但它与添加文本框相同.

另一个问题 - 尝试将表单引用为document.xxx意味着xxx是表单的名称.但无论如何,试试吧

my_form=document.createElement('FORM');
my_form.name='myForm';
my_form.method='POST';
my_form.action='http://www.another_page.com/index.htm';

my_tb=document.createElement('INPUT');
my_tb.type='TEXT';
my_tb.name='myInput';
my_tb.value='Values of my Input';
my_form.appendChild(my_tb);

my_tb=document.createElement('INPUT');
my_tb.type='HIDDEN';
my_tb.name='hidden1';
my_tb.value='Values of my hidden1';
my_form.appendChild(my_tb);
document.body.appendChild(my_form);
my_form.submit();
Run Code Online (Sandbox Code Playgroud)