I want to disable button when input field is empty and enable it back if input field is not empty.
Works when input field is empty But when I fill input field, still the button is disabled. Does not works when input field is not empty
I think this is simple logic but still I can't make it work. I am sure there must be something wrong with my logic. Should I be using events after disabling the button? How do I approach this problem? Help me.
The problem with your code is that you are checking the input value only once. Although others have suggested using the onkeyup
event the problem with that is that when a user pastes an input the button will stay disabled. We can instead use the input
event that fires every time the value changes.
let button = document.getElementById("btn")
let input = document.getElementById("task")
input.addEventListener("input", function(e) {
if(input.value.length == 0) {
button.disabled = true
} else {
button.disabled = false
}
})
<input id="task">
<button id="btn" disabled>
send
</button>