Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill in form field, and submit, using javascript?

Tags:

javascript

dom

If I have an html document whose rough structure is

<html> <head> </head> <body class="bodyclass" id="bodyid"> <div class="headerstuff">..stuff...</div> <div class = "body"> <form action="http://example.com/login" id="login_form" method="post"> <div class="form_section">You can login here</div> <div class="form_section"> <input xmlns="http://www.w3.org/1999/xhtml" class="text" id="username"        name="session[username_or_email]" tabindex="1" type="text" value="" /> </div> <div class="form_section">etc</div> <div xmlns="http://www.w3.org/1999/xhtml" class="buttons">     <button type="submit" class="" name="" id="go" tabindex="3">Go</button>     <button type="submit" class="" name="cancel"              id="cancel" tabindex="4">Cancel</button> </div> </form> </div> </body> </html> 

You can see that there is a username field and a Go button. How would I, using Javascript, fill in the username and press Go...?

I would prefer to use plain JS, rather than a library like jQuery.

like image 262
cannyboy Avatar asked Jan 13 '11 17:01

cannyboy


People also ask

How you can submit a form using JavaScript?

In javascript onclick event , you can use form. submit() method to submit form. You can perform submit action by, submit button, by clicking on hyperlink, button and image tag etc. You can also perform javascript form submission by form attributes like id, name, class, tag name as well.

How do I keep form data after submitting the form using JavaScript?

To keep the values, you must fill in the values on the server while rendering the page. Usually, you can simply copy the data from the HTML request parameters into the fields. Usually, you cannot simply copy the HTML request parameters into the fields.

How do you display submitted data on the same page as the form in JavaScript?

If you want to add content to a page you need to work with the DOM. Google "create div javascript" or "create span javascript" for examples, you basically need to create an element that has your text in it and add that element to the part of the page you want the text to display.


2 Answers

document.getElementById('username').value="moo" document.forms[0].submit() 
like image 144
Diodeus - James MacFarlane Avatar answered Sep 29 '22 03:09

Diodeus - James MacFarlane


document.getElementById('username').value = 'foo'; document.getElementById('login_form').submit(); 
like image 22
JohnO Avatar answered Sep 29 '22 03:09

JohnO