Clicking submit button of an HTML form by a Javascript code

此生再无相见时 提交于 2020-01-12 06:30:06

问题


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>

回答1:


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.)




回答2:


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



回答3:


You can do :

document.forms["loginForm"].submit()

But this won't call the onclick action of your button, so you will need to call it by hand.

Be aware that you must use the name of your form and not the id to access it.



来源:https://stackoverflow.com/questions/5211328/clicking-submit-button-of-an-html-form-by-a-javascript-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!