Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking submit button of an HTML form by a Javascript code

Tags:

I don't know much about WEB probramming, so feel free to ask if I'm missing any details.

There is a certain website which I'm visiting very frequently, and it requires users to log in every time they visit. For the login page of this website, I'm trying to write down a userscript which will automatically log me in.

I managed to fill in the form fields, but don't have any idea how to click the submit button by JavaScript. The below is a condensed version of the original login code. How can I automatically click this submit button in this code?

<div id="start">     <div id="header">         <div id="login">             <form id="loginForm" name="loginForm" method="post" action="#">                 // ...                 <input type="submit" id="loginSubmit" onclick="changeAction('submitInput','loginForm');document.forms['loginForm'].submit();" value="Log in" />                 // ...             </form>         </div>     </div> </div> 
like image 807
hkBattousai Avatar asked Mar 06 '11 15:03

hkBattousai


2 Answers

The usual way to submit a form in general is to call submit() on the form itself, as described in krtek's answer.

However, if you need to actually click a submit button for some reason (your code depends on the submit button's name/value being posted or something), you can click on the submit button itself like this:

document.getElementById('loginSubmit').click(); 
like image 106
mercurial Avatar answered Sep 29 '22 12:09

mercurial


document.getElementById('loginSubmit').submit(); 

or, use the same code as the onclick handler:

changeAction('submitInput','loginForm'); document.forms['loginForm'].submit(); 

(Though that onclick handler is kind of stupidly-written: document.forms['loginForm'] could be replaced with this.)

like image 45
Matt Ball Avatar answered Sep 29 '22 11:09

Matt Ball