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

时间:2010-10-21 19:35:15

标签: 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>

我尝试使用以下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();

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

4 个答案:

答案 0 :(得分:25)

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

my_tb.appendChild(my_form);

应该是

my_form.appendChild(my_tb);

另外,我没有看到你在哪里创建隐藏元素,但它与添加文本框是一样的。

另一个问题 - 尝试将表单引用为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();

答案 1 :(得分:2)

              var myform = document.createElement("form");

                product = document.createElement("input");
                product.value = JSProduct;
                product.name = "Product";
                myform.action = "myForm.aspx";
                myform.method = "post";
                form1.appendChild(product);
                document.body.appendChild(form1);
                form1.submit();

这将创建一个表单并且有一个子元素产品(“输入类型”),您必须将子元素附加到父元素,如产品形成和形成DOM根元素主体和文档,您可以添加一个元素形式作为行动和方法这将做你的事。

答案 2 :(得分:2)

你也可以做Saurabh Chauhan的反应但不添加动态元素到身体 这个解决方案都是动态解决方案。

    var myform = document.createElement("form");
    myform.action = "myForm.aspx";
    myform.method = "post";


    product = document.createElement("input");
    product.value = "value";
    product.name = "name";

    myform.appendChild(product);
    myform.submit();

答案 3 :(得分:1)

您可以尝试使用简单的方法:

<script type="text/javascript">document.write("[the form's HTML]");</script>
在某个地方的身体里面。然后,要提交表单,请添加:

<script type="text/javascript">document.my_form.submit();</script>

这可以防止以编程方式创建DOM时出错。

相关问题