I'm trying to make a simple post creator with a title, and I want to make the "post-btn" to be disabled and its cursor changed to "not-allowed" if one of the inputs (title, text) is empty ( value.length === 0; ), I've written a function using forEach and an eventListener but it didn't actually work, I'm thinking of another way by adding an eventListener for both inputs alone, but I couldn't imagine any short way to do it without writing a lot of if statements. So I decided to ask for help, if you can correct the mistakes I've done here or help me with a brand new effective and understandable code.
To make things more clear I'd say: if the title is empty the buttons gets disabled also if the text is empty the buttons gets disabled as well, if none of them are empty the buttons becomes enabled.
let createPostBehavior = function(){
let inputs = document.querySelectorAll('.post-input');
let postBtn = document.querySelector('.post-btn');
inputs.forEach(function(inp){
inp.addEventListener('input', function(e){
if(e.target.value.length === 0) {
postBtn.disabled = true;
postBtn.style.cursor = 'not-allowed';
} else if (e.target.value.length > 0) {
postBtn.disabled = false;
postBtn.style.cursor = 'pointer';
}
})
})
}
createPostBehavior();
<div class="create-post-wrapper">
<div>
<p class="sub-headline">Create a new post</p>
</div>
<div>
<input class="post-input" type="text" placeholder="Title">
</div>
<textarea id="input" class="post-input"></textarea>
<div class="buttons-wrapper">
<button class="post-btn">Post</button>
</div>
</div>
createPostBehavior()somewhere). The only change I'd add is thatpost-btnshould initially be disabled since both imputs are empty at the start.requiredattribute and not mess around with the disabled state of the button, but that's a different UX.