[英]Refreshing a page when user input is wrong
當用戶輸入錯誤時如何重新加載/刷新表單,因為我正在動態生成表單,我設法顯示警告消息但重置字段時遇到問題,還建議我的代碼需要任何改進?
...
JavaScript:
const div = document.querySelector(".addHere");
document.querySelector(".btn").addEventListener("click", addInputs);
function addInputs() {
const inputValue = parseInt(document.querySelector(".inputValue").value);
if (isNaN(inputValue)) {
alert("Wrong input");
const form = document.createElement("form");
form.method = "post";
form.action = "#";
} else {
for (let i = 1; i <= inputValue; i++) {
const input1 = document.createElement("input");
input1.type = "text";
input1.maxLength = "12";
input1.className = "factor";
input1.required = true;
const input2 = document.createElement("input");
input2.type = "text";
input2.maxLength = "1";
input2.className = "priority";
input2.required = true;
const br = document.createElement("br");
form.appendChild(br.cloneNode());
form.appendChild(input1);
form.appendChild(input2);
form.appendChild(br.cloneNode());
div.appendChild(form);
}
const sub = document.createElement("button");
sub.type = "submit";
sub.value = "Submit";
sub.className = "subButton";
sub.textContent = "Submit";
div.appendChild(sub);
}
}
HTML:
<div class="addHere"></div>
<div class="inputs">
<input type="text" maxlength="1" class="inputValue" placeholder="insert numbers:" />
<button class="btn">+</button>
</div>
試試這條線
document.getElementById('input').value = "";
您可以將整個表單的輸入重置為其原始值,如下所示:
<script>
document.getElementById('myform').reset();
</script>
或者只有一個像這樣的輸入元素:
<script>
document.getElementById('userName').value = '';
</script>
如果你想重新加載整個頁面,你應該這樣做:
<script>
document.location.href = document.location.href;
</script>
<form id="myform">
<input id="userName" type="text" />
</form>
這個怎么樣?
CCS:
<style>
.subButton {
display: none;
}
</style>
腳本:
<script>
window.addEventListener('load', (event) => {
document.querySelector(".btnAdd").addEventListener("click", addInputs);
});
function addInputs() {
const inputValue = parseInt(document.querySelector(".inputValue").value);
if (isNaN(inputValue) || inputValue < 1) {
alert("Wrong input");
document.querySelector(".inputValue").value = '';
} else {
let html = '';
for (let i = 1; i <= inputValue; i++) {
html += '<input type="text" maxlength="12" class="factor" required>';
html += '<input type="text" maxlength="1" class="priority" required>';
html += '<br />';
}
document.querySelector(".addHere").innerHTML = html;
document.querySelector(".subButton").style.display = 'block';
document.querySelector(".inputs").style.display = 'none';
}
}
</script>
HTML:
<body>
<form method="post" action="#">
<div class="addHere"></div>
<input type="submit" value="Submit" class="subButton" />
<div class="inputs">
<input type="text" maxlength="1" class="inputValue" placeholder="insert numbers:" />
<button type="button" class="btnAdd">+</button>
</div>
</form>
</body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.