我已经尝试了几种不同的方法,基于我在这个主题上所做的搜索,但由于某些原因,我不能让它工作。我只想让我的文本输入和文本区在我点击提交按钮后清除。
这是代码。
<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>
发布于 2013-01-30 02:00:58
您的表单已被提交,因为您的按钮是submit
类型。这在大多数浏览器中将导致表单提交和服务器响应的加载,而不是在页面上执行javascript。
将submit按钮的类型更改为button
。此外,由于此按钮被赋予id submit
,它将导致与Javascript的提交功能冲突。更改此按钮的id。试试像这样的东西
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
这个实例中的另一个问题是表单的名称包含一个-
破折号。然而,Javascript将-
翻译为减号。
您需要使用基于数组的表示法或使用document.getElementById()
/ document.getElementsByName()
。getElementById()
函数直接返回element实例,因为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
}
发布于 2017-11-09 17:56:56
既然您使用的是jquery
库,我建议您使用reset()
方法。
首先,将id属性添加到form标记
<form id='myForm'>
然后在完成时,清除您的输入字段,如下所示:
$('#myForm')[0].reset();
发布于 2013-01-30 02:01:02
您可以尝试这样做:
function submitForm() {
$('form[name="contact-form"]').submit();
$('input[type="text"], textarea').val('');
}
此脚本需要在页面上添加jquery。
https://stackoverflow.com/questions/14589193
复制相似问题