Szu*_*ron 15 javascript jquery html5
我已经尝试了几种不同的方式,基于我在这个主题上所做的搜索,由于某种原因我无法让它工作.我只想在输入提交按钮后清除文本输入和textarea.
这是代码.
<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>
Run Code Online (Sandbox Code Playgroud)
Kam*_*ami 29
当您的按钮类型时,您的表单已经提交submit.在大多数浏览器中,这将导致表单提交和加载服务器响应,而不是在页面上执行javascript.
将提交按钮的类型更改为button.此外,由于此按钮被赋予id submit,它将导致与Javascript的提交功能冲突.更改此按钮的ID.尝试类似的东西
<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">
Run Code Online (Sandbox Code Playgroud)
此实例中的另一个问题是表单的名称包含-破折号.但是,Javascript翻译-为减号.
您需要使用基于数组的表示法或使用document.getElementById()/ document.getElementsByName().该getElementById()函数直接返回元素实例,因为Id是唯一的(但它需要设置Id).该getElementsByName()返回具有相同名称的值的阵列.在这种情况下,由于我们没有设置id,我们可以使用getElementsByNamewith索引0.
请尝试以下方法
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
}
Run Code Online (Sandbox Code Playgroud)
Aki*_*imi 10
由于您使用的是jquery图书馆,我建议您使用该reset()方法。
首先,给form标签添加一个id属性
<form id='myForm'>
Run Code Online (Sandbox Code Playgroud)
然后完成后,将输入字段清除为:
$('#myForm')[0].reset();
Run Code Online (Sandbox Code Playgroud)
小智 8
您可以HTMLFormElement.prototype.reset按照MDN使用
document.getElementById("myForm").reset();
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以分配给该onsubmit属性:
document.querySelector('form').onsubmit = e => {
e.target.submit();
e.target.reset();
return false;
};
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit
| 归档时间: |
|
| 查看次数: |
129296 次 |
| 最近记录: |