在此表单中,我将提交按钮设置为禁用,直到表单字段完成为止。当按下提交按钮时,preventDefault() 运行,并显示警报。关闭该警报后,表单将重置,但按钮状态不会返回到禁用状态。
//validate form input
function validateForm() {
let formCheck = document.forms['myForm'].elements;
let canSubmit = true;
for (let i = 0; i < formCheck.length; i++) {
if (formCheck[i].value.length == 0) canSubmit = false;
}
submitThis.disabled = !canSubmit;
}
//prevent form submission, alert if form is submitted, reset form
document.getElementById('submitThis').addEventListener('click', function(e) {
e.preventDefault();
alert('Awesomeness! The form will now reset.');
myForm.reset();
})
body {
font-family: sans-serif;
margin: 0;
padding: 0;
height: 100vh;
}
h2 {
text-align: center;
}
form {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
}
form input {
margin: 0.5em 0;
padding: 0.5em;
border-radius: 5px;
}
form input[type=submit]:active {
background-color: darkblue;
color: white;
}
<form name="myForm" id="myForm" action="/">
<h3>My Form</h3>
<input type="text" id="fName" placeholder="First Name" onkeyup="validateForm()" />
<input type="text" id="address" placeholder="Street Address" onkeyup="validateForm()" />
<input type="text" id="addCity" placeholder="City" onkeyup="validateForm()" />
<input type="text" id="addState" placeholder="State" onkeyup="validateForm()" />
<input type="number" id="addZip" placeholder="Zip Code" onkeyup="validateForm()" />
<!-- submit form -->
<input type="submit" id="submitThis" value="Submit" disabled="disabled"/>
</form>
largeQ
弑天下
慕尼黑5688855
相关分类