【问题标题】:How to create a form dynamically using JavaScript?如何使用 JavaScript 动态创建表单?
【发布时间】:2011-04-28 19:39:08
【问题描述】:

我想使用 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();

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

【问题讨论】:

  • 也许你应该只使用.innerHTML...
  • .innerHTML 的问题在于您尝试提交表单时。您将没有对表单的引用,并且它可能尚未添加到 DOM。

标签: javascript forms


【解决方案1】:

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

my_tb.appendChild(my_form);

应该是

my_form.appendChild(my_tb);

另外,我看不到您尝试在哪里创建隐藏元素,但这与添加文本框相同。

另一个问题 - 试图将表单引用为 document.xxx 意味着 xxx 是表单的 name。不过还是试试吧

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】:

你也可以做 Saurabh Chauhan 响应,但不向 body 添加动态元素 这个解决方案都是动态解决方案。

    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();

【讨论】:

  • 如果myform 未附加到document.body,则不会执行submit()。只要我添加document.body.appendChild(myform);,你的代码也可以工作。
【解决方案3】:
              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 根元素主体和文档,您可以添加作为动作和方法的形式这会做你的事。

【讨论】:

  • 不知道为什么要创建myform,然后再使用form1
  • 如何在 post 函数中添加参数?
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多