我想检查我的所有输入是否都已填写以激活提交按钮,但使用我的代码它只检查一个输入。
我的 HTML(带有 TWIG):
<div class="content-wrapper content-wrapper--close">
<form class="form form--width">
<fieldset class="form__fieldset input">
<input class="input__field" id="name" name="name"/>
<label class="input__label" for="name">Nom et prénom</label>
</fieldset>
<fieldset class="form__fieldset input">
<input class="input__field" id="structure" name="structure"/>
<label class="input__label" for="structure">Structure</label>
</fieldset>
<fieldset class="form__fieldset input">
<input class="input__field" id="email" name="email"/>
<label class="input__label" for="email">Adresse email</label>
</fieldset>
<fieldset class="form__fieldset input">
<textarea class="input__field input__field--textarea" name="message" id="message" rows="10">
</textarea>
<label class="input__label" for="message">Message</label>
</fieldset>
<fieldset class="form__fieldset">
<div class="cta is-disabled">
<input type="submit" class="cta__link button" value="Envoyer">
</div>
</fieldset>
</form>
</div>
我的 JavaScript:
/**
* Add event listener on input.
*
* @param form
*/
addListener(form) {
const inputs = form.querySelectorAll('.input__field');
[...inputs].map( input => {
input.addEventListener('focus', (event) => {
event.target.classList.add('is-fill');
});
input.addEventListener('blur', (event) => {
if (event.target.value === '') {
event.target.classList.remove('is-fill');
}
});
});
}
// // If all fields are filled, remove class 'is-disabled'
handleInputs(items) {
const inputs = items.querySelectorAll('.input__field');
const submitButton = document.querySelector('.form .cta');
[...inputs].map( input => {
input.addEventListener('input', (e) => {
if(e.target.value !== '') {
submitButton.classList.remove('is-disabled');
} else {
if(!submitButton.classList.contains('is-disabled')) {
submitButton.classList.add('is-disabled');
}
}
});
});
}
目前它仅适用于一个输入,我不知道如何检查所有输入。如果有人可以帮助我,我找不到任何答案。 谢谢
最佳答案
使用 HTML5,您可以在表单无效时设置表单按钮的样式。简单的 CSS 规则,它将应用样式。默认情况下,它还会阻止表单提交。
在表单中填写有效的姓名、电子邮件和日期之前,该按钮将保持红色。我还添加了一条规则,可以更改您的代码也在编辑的当前元素。
input {
margin: .5rem;
}
input:focus {
box-shadow: 0px 0px 5px 5px #0ff;
}
form:invalid input[type="submit"] {
background-color: red
}
<form>
<fieldset>
<legend>User:</legend>
<label for="name">Name:</label>
<input type="text" id="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" required><br>
<label for="dob">Date of birth:</label>
<input type="date" id="bod" required>
</fieldset>
<input type="submit" />
</form>
关于javascript - 如何检查表单的所有字段是否已填写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57925685/