2010-10-21 38 views
16

我想使用JavaScript動態地在HTML頁面的任何位置創建一個不可見的表單,然後自動提交。
我想創建如下形式:如何使用JavaScript動態創建表單?

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

但不工作?我怎樣才能做到這一點?請幫忙。

+0

也許您應該只使用'.innerHTML' ... – kennytm 2010-10-21 19:38:15

+0

.innerHTML的問題是當您嘗試提交表單時。您不會有對錶單的引用,並且它可能尚未添加到DOM。 – 2010-10-21 19:42:13

回答

22

您將表單元素添加爲文本框的子元素。

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

毆打我!從幾秒鐘:) +1 – AlexV 2010-10-21 19:39:51

+0

仍然無法正常工作... – chanchal1987 2010-10-21 19:49:46

+0

謝謝...它的工作... – chanchal1987 2010-10-21 20:07:06

1

你可以嘗試使用的簡單的方法:

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

體內某處。然後,要提交表單,請添加:

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

這樣可以防止在以編程方式創建DOM時出現錯誤。

+0

我的文檔不是空白。它已經有一些內容。 – chanchal1987 2010-10-21 19:45:57

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根elemnt身體和文檔,你可以添加表單作爲操作和方法這將做你的事情。

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

如果'myform'沒有附加到'document.body','submit()'不會被執行。只要我添加'document.body.appendChild(myform);',你的代碼也可以工作。 – NoRyb 2016-06-23 07:23:50

相關問題