Javascript: Empty input with attribute required
Solution 1:
This code should work.
Several weird things I think you should change.
- You doesn't have the
eventListener
, so once the document load, it will check if the input has value or not (which always be""
) - You have several things in the
input
hasrequired
attribute, so you have to usequerySelectorAll
instead ofquerySelector
and a loop to loop it
document.querySelectorAll('[required]').forEach(item=>{
item.addEventListener('change',check)
window.addEventListener('load',check)
})
function check(){
for(let i of document.querySelectorAll('[required]')){
if (!i.value) {
document.querySelector('.button').disabled = true;
break;
} else {
document.querySelector('.button').disabled = false;
}
}
}
.button {
color: #fff;
background-color: #007bff;
border: none;
display: inline-block;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
cursor: pointer;
}
.button:disabled {
color: #a2a5a9;
border-color: #c9ced3;
background-color: #f2f2f2;
cursor: text;
}
<form class="form" id="form">
<input type="number" id="a" class="a" placeholder="000" required>
<input type="number" id="b" class="b" placeholder="0">
<input type="number" id="c" class="c" placeholder="000" required>
<input type="number" id="d" class="d" placeholder="000" required>
<input type="number" id="e" class="e" placeholder="0">
</form>
<button type="submit" value="Ok" id="send" class="button">Ok</button>