我正在尝试使用纯JavaScript,而不是jquery。我有一个具有ID表单并在其中包含表单的div。提交表单后,如何清空此div的内容并将其替换为提交的文本表单?
<div class="form">
<form action="">
...
</form>
</div>
答案 0 :(得分:0)
侦听表单上的submit
事件,然后替换容器的innerHTML
。
document.addEventListener('DOMContentLoaded', function() {
const formContainer = document.querySelector('.form');
const form = formContainer.querySelector('form');
form.addEventListener('submit', function () {
formContainer.innerHTML = `Thank you for telling me about ${form.someInput.value}`;
});
});
<div class="form">
<form>
<input name="someInput" type="text" />
<button type="submit">submit</button>
</form>
</div>
答案 1 :(得分:0)
为表单及其周围的div提供ID:
<div class="form" id="form-wrapper">
<form id="my-form" action="#">
</form>
</div>
和您要求的JavaScript:
var submitted = function(e){
var d = document.getElementById("form-wrapper");
d.innerHTML = "Form Submitted";
e.preventDefault();
}
var ele = document.getElementById("my-form");
if(ele.addEventListener){
ele.addEventListener("submit", submitted, false); //Modern browsers
}else if(ele.attachEvent){
ele.attachEvent('onsubmit', submitted); //Old IE
}
但是请记住,在这里我们只是阻止表单的提交,所以我猜您将需要在submitted
函数内添加一些AJAX处理。
答案 2 :(得分:0)
这里有几件事要注意...
<div>
例如,在文档底部的<script>
标签中的</body>
...
let div = document.querySelector('.form') // find the first element by class
let form = div.querySelector('form') // find the form by tag
form.addEventListener('submit', e => {
// stop the page navigating away
e.preventDefault()
// submit the form via AJAX
fetch(form.action, {
method: form.method
body: new FormData(form)
}).then(res => {
// now update the <div> contents
div.innerHTML = res.ok ? 'Form Submitted' : 'Form submit failed'
})
})
注意,这会将表单提交为multipart/form-data
。如果您的后端只期望application/x-www-form-urlencoded
,则需要做更多的工作。参见How do I post form data with fetch api?