[英]How to hide form button if two input fields have the same sentences
我有一個 HTML 表單,如果兩個字段具有相同的 for,則禁用提交按鈕,但我希望隱藏提交按鈕,請問我該怎么做?
<form id="my-form" action="" method="post">
<input type="text" id="inp-1" value="">
<input type="text" id="inp-2" value="">
<button type="submit">Signup project</button>
</form>
<script>
/** select the form and both the inputs, select them once and use them as many as needed */
const myForm = document.getElementById('my-form'),
inp1 = document.getElementById('inp-1'),
inp2 = document.getElementById('inp-2');
/**
* listen for "submit" events on the form
* if the trimmed values of both the inputs is the same then we prevent the form from being submitted
*/
myForm.addEventListener('submit', e => inp1.value.trim() === inp2.value.trim() && e.preventDefault());
</script>
這將解決問題。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form id="my-form" action="" method="post">
<input type="text" id="inp-1" value="" />
<input type="text" id="inp-2" value="" />
<button type="submit" id="submit">Signup project</button>
</form>
</body>
<script>
const myForm = document.getElementById("my-form"),
inp1 = document.getElementById("inp-1"),
inp2 = document.getElementById("inp-2");
submitBtn = document.getElementById("submit");
inp1.addEventListener("input", (e) => {
const val = e.target.value;
if (val.length > 1 && inp2.value.length > 1) {
if (val == inp2.value) {
submitBtn.style.display = "none";
} else {
submitBtn.style.display = "inline";
}
}
});
inp2.addEventListener("input", (e) => {
const val = e.target.value;
if (val.length > 1 && inp1.value.length > 1) {
if (val == inp1.value) {
submitBtn.style.display = "none";
} else {
submitBtn.style.display = "inline";
}
}
});
// myForm.addEventListener(
// "submit",
// (e) => inp1.value.trim() === inp2.value.trim() && e.preventDefault()
// );
</script>
</html>
希望它有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.