Javascript 如何使用javascript填写表单字段并提交?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4683331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:36:49  来源:igfitidea点击:

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

javascriptdom

提问by cannyboy

If I have an html document whose rough structure is

如果我有一个 html 文档,它的粗略结构是

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

您可以看到有一个用户名字段和一个 Go 按钮。我将如何使用 Javascript 填写用户名并按 Go...?

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

我更喜欢使用普通的 JS,而不是像 jQuery 这样的库。

回答by Diodeus - James MacFarlane

document.getElementById('username').value="moo"
document.forms[0].submit()

回答by JohnO

document.getElementById('username').value = 'foo';
document.getElementById('login_form').submit();

回答by Chandu

You can try something like this:

你可以尝试这样的事情:

    <script type="text/javascript">
        function simulateLogin(userName)
        {
            var userNameField = document.getElementById("username");
            userNameField.value = userName;
            var goButton = document.getElementById("go");
            goButton.click();
        }

        simulateLogin("testUser");
</script>

回答by xaoax

It would be something like:

它会是这样的:

document.getElementById("username").value="Username";
document.forms[0].submit()

Or similar edit: you guys are too fast ;)

或类似的编辑:你们太快了;)

回答by NIRANJAN GOWDA C M

This method helped me doing this task

这种方法帮助我完成了这项任务

document.forms['YourFormNameHere'].elements['NameofFormField'].value = "YourValue"
document.forms['YourFormNameHere'].submit();