javascript - 提交后清除我的表单输入

标签 javascript jquery html

我已经根据我对该主题所做的搜索尝试了几种不同的方法,但由于某种原因我无法让它工作。我只想在点击提交按钮后清除我的文本输入和文本区域。

这是代码。

<div id="sidebar-info">
    <form name="contact-form" action="formprocess.php" method="post" target="ninja-frame">
        <h1>By Phone</h1>
        <p id="by-phone">XXX-XXX-XXXX</p>
        <h1>By Email</h1>
        <p id="form-row">Name</p>
        <input name="name" id="name" type="text" class="user-input" value="">
        <p id="form-row">Email</p>
        <input name="email" id="email" type="text" class="user-input" value="">
        <p id="form-row">Message</p>
        <textarea name="message" id="message" class="user-input" rows="10" maxlength="1500"></textarea>
        <p>*Please fill out every field</p>
        <input type="submit" value="Submit" id="submit" onclick="submitForm()">

        <script>
            function submitForm() {
            document.contact-form.submit();
            document.contact-form.reset();
            }
        </script>
    </form>
</div>

最佳答案

您的表单已经提交,因为您的按钮是 submit。在大多数浏览器中,这会导致提交表单并加载服务器响应,而不是在页面上执行 javascript。

将提交按钮的类型更改为按钮。此外,由于此按钮的 ID 为 submit,因此它会与 Javascript 的提交功能发生冲突。更改此按钮的 ID。尝试类似的东西

<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">

此实例中的另一个问题是表单的名称包含一个 - 破折号。但是,Javascript 将 - 翻译成减号。

您将需要使用基于数组的表示法或使用 document.getElementById()/document.getElementsByName()getElementById() 函数直接返回元素实例,因为 Id 是唯一的(但它需要设置一个 Id)。 getElementsByName() 返回一组具有相同名称的值。在这种情况下,因为我们没有设置 id,我们可以使用索引为 0 的 getElementsByName

尝试以下操作

function submitForm() {
   // Get the first form with the name
   // Usually the form name is not repeated
   // but duplicate names are possible in HTML
   // Therefore to work around the issue, enforce the correct index
   var frm = document.getElementsByName('contact-form')[0];
   frm.submit(); // Submit the form
   frm.reset();  // Reset all form data
   return false; // Prevent page refresh
}

关于javascript - 提交后清除我的表单输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14589193/

相关文章:

javascript - Requirejs模块重新定义

javascript - 如何正确回收 JavaScript 中的缓冲区

javascript - 与 requirejs 连接并排除单个文件?

javascript - 如何获取某些类的子div的父级的多个索引

javascript - 使用 Highcharts 在网页上创建图表

javascript - 如何在对对象数组进行排序后再次反向排序?

jquery - 计算有多少个 div 具有特定内容?

jquery - 设置标题时 Photoswipe 和 jQuery 错误

html - css 类覆盖样式 html 片段

javascript - 在表单提交上更改/添加表单值