views:

32

answers:

3

I want to create a invisible form anywhere into a HTML page dynamically using JavaScript and then submit automatically.
I want to create the form given below:

<form name='myForm' method='post' action='http://www.another_page.com/index.htm'&gt;
<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>

I tried using the JavaScript below:

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

But not working? How can I do that? Please help.

+4  A: 

You're adding the form element as a child of the text box.

my_tb.appendChild(my_form);

Should be

my_form.appendChild(my_tb);

Also, I don't see where you're trying to create the hidden elements, but it's the same thing as adding a text box.

Another problem - trying to reference the form as document.xxx means that xxx is the name of the form. But anyway, try

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();
Sam Dufel
Beated me! from a few secs :) +1
AlexV
Still not working...
chanchal1987
Thanks... Its working...
chanchal1987
A: 

You could try the simple approach of using:

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

inside the body somewhere. Then, to submit the form, add:

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

This prevents mistakes when creating the DOM programmatically.

Evan Mulawski
My document is not blank. It already have some content.
chanchal1987
A: 

try these

http://www.tizag.com/javascriptT/javascript-innerHTML.php

http://javascript.about.com/library/blwrite.htm

zod
Actually I don't know the content of the BODY tag. Then how can I use innerHTML?
chanchal1987