ZetCode

JavaScript form.submit

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 form.submit 方法。此方法允许开发人员以编程方式提交 HTML 表单,从而实现动态表单处理和增强的用户体验。

基本定义

form.submit() 方法以编程方式提交表单,无需单击提交按钮。它会触发表单的提交过程,就像点击了提交按钮一样。

当您需要根据特定条件或事件提交表单时,此方法非常有用。它可以绕过表单标记中对物理提交按钮的需求。

基本 form.submit

此示例演示了如何以编程方式提交简单表单。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic form.submit</title>
</head>
<body>

<form id="myForm" action="/submit" method="post">
    <input type="text" name="username" placeholder="Username">
</form>

<button onclick="submitForm()">Submit Form</button>

<script>
    function submitForm() {
        const form = document.getElementById('myForm');
        form.submit();
    }
</script>

</body>
</html>

在此基本示例中,我们有一个带有 ID 的表单和一个单独的按钮。JavaScript 代码使用 getElementById 检索表单,并在单击按钮时在其上调用 submit()

这演示了 form.submit() 以编程方式触发表单提交的基本用法。表单将以 POST 方法提交到指定的 action URL。

带验证的表单提交

此示例显示了如何在提交前验证表单数据。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation</title>
</head>
<body>

<form id="loginForm" action="/login" method="post">
    <input type="text" id="username" name="username" placeholder="Username">
    <input type="password" id="password" name="password" placeholder="Password">
</form>

<button onclick="validateAndSubmit()">Login</button>
<p id="error" style="color:red"></p>

<script>
    function validateAndSubmit() {
        const form = document.getElementById('loginForm');
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const errorElement = document.getElementById('error');
        
        if (!username || !password) {
            errorElement.textContent = 'Both fields are required!';
            return;
        }
        
        errorElement.textContent = '';
        form.submit();
    }
</script>

</body>
</html>

这里我们有一个带验证的登录表单。validateAndSubmit 函数在允许提交之前检查两个字段是否都已填写。

这演示了在验证后如何使用 form.submit()。表单仅在满足所有条件时才提交,与默认表单提交相比,提供了更好的用户反馈。

延迟表单提交

此示例演示了在延迟后提交表单。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Delayed Submission</title>
</head>
<body>

<form id="surveyForm" action="/survey" method="post">
    <textarea name="feedback" placeholder="Your feedback..."></textarea>
</form>

<button onclick="startCountdown()">Submit Feedback</button>
<p id="countdown"></p>

<script>
    function startCountdown() {
        const countdownElement = document.getElementById('countdown');
        let seconds = 5;
        
        countdownElement.textContent = `Submitting in ${seconds} seconds...`;
        
        const interval = setInterval(() => {
            seconds--;
            countdownElement.textContent = `Submitting in ${seconds} seconds...`;
            
            if (seconds <= 0) {
                clearInterval(interval);
                document.getElementById('surveyForm').submit();
            }
        }, 1000);
    }
</script>

</body>
</html>

在此示例中,单击按钮会在表单提交前启动 5 秒倒计时。用户可以在表单提交前看到倒计时进度。

这显示了如何将 form.submit() 与计时函数结合使用以创建延迟提交。这种模式对于确认对话框或最后编辑机会很有用。

多个表单提交

此示例显示了如何使用一个按钮提交多个表单。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Multiple Forms</title>
</head>
<body>

<form id="form1" action="/save1" method="post" target="_blank">
    <input type="text" name="data1" placeholder="Data for form 1">
</form>

<form id="form2" action="/save2" method="post" target="_blank">
    <input type="text" name="data2" placeholder="Data for form 2">
</form>

<button onclick="submitAllForms()">Save All Data</button>

<script>
    function submitAllForms() {
        document.getElementById('form1').submit();
        document.getElementById('form2').submit();
        alert('Both forms submitted!');
    }
</script>

</body>
</html>

这里我们有两个独立的表单,它们可以通过一次按钮点击同时提交。每个表单都有自己的 action URL,并将独立提交。

这演示了 form.submit() 如何处理多个表单。请注意,由于 target="_blank" 属性,表单在新标签页中打开,这可以防止从当前页面导航。

AJAX 替代 form.submit

此示例显示了传统表单提交的 AJAX 替代方案。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>AJAX Form Submission</title>
</head>
<body>

<form id="ajaxForm">
    <input type="text" name="email" placeholder="Your email">
    <button type="button" onclick="submitViaAJAX()">Subscribe</button>
</form>

<p id="result"></p>

<script>
    function submitViaAJAX() {
        const form = document.getElementById('ajaxForm');
        const formData = new FormData(form);
        const resultElement = document.getElementById('result');
        
        fetch('/subscribe', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            resultElement.textContent = data.message;
            resultElement.style.color = 'green';
        })
        .catch(error => {
            resultElement.textContent = 'Error: ' + error.message;
            resultElement.style.color = 'red';
        });
    }
</script>

</body>
</html>

此示例使用 Fetch API 异步提交表单数据,无需重新加载页面。使用 promises 处理响应,为用户提供反馈。

虽然不直接使用 form.submit(),但这展示了一种现代替代方案。AJAX 提交通过避免完全页面重新加载并实现更动态的响应,提供了更好的用户体验。

来源

MDN form.submit 文档

在本文中,我们展示了如何在 JavaScript 中使用 form.submit()。此方法对于 Web 开发中的以编程方式处理表单至关重要,可在表单提交工作流中提供灵活性。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 JS DOM 教程