代码之家  ›  专栏  ›  技术社区  ›  chanchal1987

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

  •  17
  • chanchal1987  · 技术社区  · 15 年前

    我想使用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 回复  |  直到 15 年前
        1
  •  25
  •   Sam Dufel    10 年前

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

    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();
    
        2
  •  2
  •   Saurabh Chauhan    12 年前
                  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();
    

    这会帮到你的。

        3
  •  2
  •   josepmra    11 年前

    你也可以做Saurabh-Chauhan反应,但不需要在身体中添加dinamic元素 这个溶液都是双胺溶液。

        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();
    
        4
  •  1
  •   Evan Mulawski    15 年前

    <script type="text/javascript">document.write("[the form's HTML]");</script>
    

    在身体的某个地方。然后,要提交表单,请添加:

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

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