Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable a button if empty input

I would like the "Send" button to be disabled if the input is empty. I want to manage this in the JavaScript file. I know that it is possible in HTML to call a function on the input but I prefer to use an event in the js file.

https://codepen.io/leakcim-web/pen/gOYPpqo

//javascript
let inputElt = document.getElementById('input');
let btn = document.getElementById('button');

if (inputElt.value !== '') {
  btn.disabled = false;
} else {
  btn.disabled = true;
}
<input placeholder="Enter some text" name="name" id='input' />
<button id='button'>Réserver</button>
like image 989
Leakcim Avatar asked Apr 26 '26 01:04

Leakcim


1 Answers

You can use addEventListener to add an event to the textbox and enable/disable as appropriate

let inputElt = document.getElementById('input');
let btn = document.getElementById('button');

inputElt.addEventListener("input", function(){
  btn.disabled = (this.value === '');
})
<input placeholder="Enter some text" name="name" id='input'/>
<button id='button' disabled>Réserver</button>
like image 81
Jamiec Avatar answered Apr 28 '26 15:04

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!