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

can*_*boy 36 javascript dom

如果我有一个粗略结构的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>
Run Code Online (Sandbox Code Playgroud)

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

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

Dio*_*ane 49

document.getElementById('username').value="moo"
document.forms[0].submit()
Run Code Online (Sandbox Code Playgroud)


Joh*_*hnO 16

document.getElementById('username').value = 'foo';
document.getElementById('login_form').submit();
Run Code Online (Sandbox Code Playgroud)


Cha*_*ndu 5

您可以尝试如下操作:

    <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>
Run Code Online (Sandbox Code Playgroud)