我有一个简单的表单,其中一些输入标记有required
,如何在有效或无效的特定输入中添加类invalid
或valid
?
只有1个输入接收invalid
类。
const $input = document.querySelector("input")
const $form = document.querySelector("#form")
const $button = document.querySelector("#button")
$button.addEventListener('click', () => validate())
const validate = () => {
if (!$form.checkValidity()) {
console.log('invalid')
$input.classList.add('invalid')
} else {
console.log('valid')
$input.classList.add('valid')
}
}
input.invalid {
background: red;
}
input.valid {
background: green;
}
<form id="form">
<input class="input" type="text" placeholder="Name" name="nome" required>
<input class="input" type="number" placeholder="Number" name="number">
<input class="input" type="number" placeholder="Size" name="size" required>
<input class="input" type="checkbox" name="blue">
<input class="input" type="checkbox" name="red">
</form>
<button id="button">Submit</button>
答案 0 :(得分:0)
使用querySelectorAll
const $input = document.querySelectorAll("input")
const $form = document.querySelector("#form")
const $button = document.querySelector("#button")
$button.addEventListener('click', () => validate())
const validate = () => {
if (!$form.checkValidity()) {
console.log('invalid')
$input.forEach(input => input.classList.add('invalid'));
} else {
console.log('valid')
$input.forEach(input => input.classList.add('valid''));
}
}
input.invalid {
background: red;
}
input.valid {
background: green;
}
<form id="form">
<input class="input" type="text" placeholder="Name" name="nome" required>
<input class="input" type="number" placeholder="Number" name="number">
<input class="input" type="number" placeholder="Size" name="size" required>
<input class="input" type="checkbox" name="blue">
<input class="input" type="checkbox" name="red">
</form>
<button id="button">Submit</button>